[英]Mockito - How to mock equality?
I have the below conditional statement which I need to mock.我有以下需要模拟的条件语句。 Is it possible to mock this using mockito?
是否可以使用 mockito 来模拟它?
if (events.size() == rowsAffected) {
// app logic
}
Here the events
are of type List<Map<String, Object>>
which will be returned from a function.这里的
events
是List<Map<String, Object>>
类型,将从 function 返回。
rowsAffected
is of type int
which will also be returned by a method. rowsAffected
是int
类型,它也将由方法返回。
List<Map<String, Object>> events = service.getEvents();
int rowsAffected = service.updateEventStatus(events);
When you need to mock a method with custom behavior, you can use answer
.当您需要模拟具有自定义行为的方法时,可以使用
answer
。 Example:例子:
public class MockMe {
public String hello(String name) {
return "Hello " + name;
}
}
@Test
public void testCase() {
List<Map<String, Object>> events = service.getEvents();
int rowsAffected = service.updateEventStatus(events);
Answer<String> myMockedAnswer = invocation -> {
if (events.size() == rowsAffected) {
return "mock good";
}
return "mock bad";
};
MockMe mockMe = mock(mockMe);
doAnswer(myMockedAnswer)
.when(mockMe).hello(anyString());
assertEquals("mock good", mockMe.hello("anything"));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.