3 回答
TA贡献1802条经验 获得超5个赞
您可以在Mockito中创建答案。假设我们有一个名为Application的接口,该接口带有方法myFunction。
public interface Application {
public String myFunction(String abc);
}
这是带有Mockito答案的测试方法:
public void testMyFunction() throws Exception {
Application mock = mock(Application.class);
when(mock.myFunction(anyString())).thenAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
return (String) args[0];
}
});
assertEquals("someString",mock.myFunction("someString"));
assertEquals("anotherString",mock.myFunction("anotherString"));
}
从Mockito 1.9.5和Java 8开始,使用lambda函数提供了一种更简单的方法:
when(myMock.myFunction(anyString())).thenAnswer(i -> i.getArguments()[0]);
TA贡献1789条经验 获得超10个赞
我有一个非常类似的问题。目的是模拟一个持久化对象并可以按其名称返回的服务。该服务如下所示:
public class RoomService {
public Room findByName(String roomName) {...}
public void persist(Room room) {...}
}
服务模拟使用地图存储Room实例。
RoomService roomService = mock(RoomService.class);
final Map<String, Room> roomMap = new HashMap<String, Room>();
// mock for method persist
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
Object[] arguments = invocation.getArguments();
if (arguments != null && arguments.length > 0 && arguments[0] != null) {
Room room = (Room) arguments[0];
roomMap.put(room.getName(), room);
}
return null;
}
}).when(roomService).persist(any(Room.class));
// mock for method findByName
when(roomService.findByName(anyString())).thenAnswer(new Answer<Room>() {
@Override
public Room answer(InvocationOnMock invocation) throws Throwable {
Object[] arguments = invocation.getArguments();
if (arguments != null && arguments.length > 0 && arguments[0] != null) {
String key = (String) arguments[0];
if (roomMap.containsKey(key)) {
return roomMap.get(key);
}
}
return null;
}
});
现在,我们可以在此模拟上运行测试。例如:
String name = "room";
Room room = new Room(name);
roomService.persist(room);
assertThat(roomService.findByName(name), equalTo(room));
assertNull(roomService.findByName("none"));
添加回答
举报