在 Eclipse 中,使用 junit 和 Mockito。 我试图测试一个方法是否返回特定大小的列表,但出现以下错误:
org.mockito.exceptions.misusing.MissingMethodInvocationException: when() requires an argument which has to be 'a method call on a mock'. For example: when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because: 1. you stub either of: final/private/equals()/hashCode() methods. Those methods cannot be stubbed/verified. 2. inside when() you don't call method on mock but on some other object.
我的测试:
class ValidateBookResultsTests {
public static ArrayList<Book> searchResults = new ArrayList<Book>();
public static List<Book> topFive;
public static ArrayList<String> authors = new ArrayList<String>();
public static Book book1;
public static Book book2;
public static Book book3;
public static Book book4;
public static Book book5;
public static Book book6;
@BeforeEach
public void setUp() {
book1 = new Book("title1", authors, "publisher1");
book2 = new Book("title2", authors, "publisher2");
book3 = new Book("title3", authors, "publisher3");
book4 = new Book("title4", authors, "publisher4");
book5 = new Book("title5", authors, "publisher5");
book6 = new Book("title6", authors, "publisher6");
searchResults.add(book1);
searchResults.add(book2);
searchResults.add(book3);
searchResults.add(book4);
searchResults.add(book5);
searchResults.add(book6);
}
@Test
public void returnFiveBooksFromSearchResults() {
authors.add("John Doe");
authors.add("Bill Gates");
BookSearch mockBookSearch = Mockito.mock(BookSearch.class);
Mockito.when(mockBookSearch.returnFiveBooks(searchResults)).thenReturn(topFive);
System.out.println("return books: " + mockBookSearch.returnFiveBooks(searchResults));
System.out.println("top: "+ topFive);
assertEquals(topFive.size(), 5);
}
}
我的相关代码:
public static List<Book> returnFiveBooks(ArrayList<Book> searchResults) {
Collections.shuffle(searchResults);
topFive = searchResults.subList(0, 5);
printFiveResults();
return topFive; }
我读过其他解决方案,说要创建一个模拟类/对象,我相信我已经完成了 “BookSearch mockBookSearch = Mockito.mock(BookSearch.class);”
我错过了什么?
最佳答案
错误消息告诉您,您的方法调用不是模拟上的方法调用。
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
为什么?因为您正在尝试模拟静态方法。
Mockito.when(mockBookSearch.returnFiveBooks(searchResults)).thenReturn(topFive);
这相当于:
Mockito.when(BookSearch.returnFiveBooks(searchResults)).thenReturn(topFive);
Mockito 不能用于模拟静态方法。
这解释了您收到的错误。
但您的代码更根本的问题是您有一个正在测试的方法,并在测试中模拟它。这毫无意义。您应该模拟您的方法使用的协作者(您的代码中没有)。
要测试 returnFiveBooks
你根本不需要模拟:
@Test
public void returnFiveBooksFromSearchResults() {
var topFive = BookSearch.returnFiveBooks(searchResults);
assertEquals(topFive.size(), 5);
}
编辑:从 Mockito 3.4.0 开始支持模拟静态方法
关于java - 如何使用 when()... 解决此 Mockito MissingMethodInitationException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61506968/