[英]Java jUnit: how to assert that all objects in a list are from a certain class?
I've built the following class: 我建立了以下课程:
public class BibliotecaApp {
public static void main(String[] args) {
System.out.print("Welcome!");
}
public static ArrayList<Book> getBooksList(){
return new ArrayList();
}
}
I need to test if the method getBooksList()
return an actual list of books. 我需要测试方法
getBooksList()
返回实际的书籍列表。
I wrote the following test: 我写了以下测试:
@Test
public void everyItemInTheBookListIsABookInstance() throws Exception{
assertThat(BibliotecaApp.getBooksList(), everyItem(isA(Book.class)));
}
The test is passing - and it shouldn't. 测试通过了,但没有通过。 Note that in the actual method I return an instance of
ArrayList
(I'm practing TDD), although I defined the method signature as ArrayList<Book>
- is that why the test passes? 请注意,尽管我将方法签名定义为
ArrayList<Book>
,但在实际方法中我返回了ArrayList
的实例(我正在练习TDD)-这就是为什么测试通过? If so, how should I write a test to ensure that every item in the listem belong to a certain class ( Book
in this context)? 如果是这样,我应该如何编写测试以确保listem中的每个项目都属于某个类(在这种情况下为
Book
)?
Thanks in advance. 提前致谢。
The behaviour of everyItem
is documented as : 的行为
everyItem
被记录为 :
only matches when [...] items [...] are all matched
仅在所有项目都匹配时才匹配。
So an empty list will always match. 因此,空列表将始终匹配。
If that's a weird diea, then another way to think about it is that everyItem
fails only if it finds an item that doesn't match the inner matcher. 如果那是一个奇怪的死者,那么思考它的另一种方法是,仅当
everyItem
找到与内部匹配项不匹配的项目时,它everyItem
失败。 1 There are no such items in an empty list. 1空列表中没有此类项目。
If you want the test to fail if there are no items at all, then you'll also 2 need to assert that explicitly: 如果您希望测试在没有任何项目的情况下失败,那么您还需要2明确声明这一点:
assertThat(BibliotecaApp.getBooksList(), not(empty()));
1. Even if one doesn't agree on that equivalence, one can take a look at the implementation to see that this is indeed what's happening. 1.即使人们不同意这种等效性,也可以看一下实现,以确保确实如此。
2. But you may as well drop the original assertion, because the compiler already enforces the type. 2.但是您也可以删除原始断言,因为编译器已经强制执行了该类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.