猿问

使模拟方法返回传递给它的参数

考虑如下方法签名:


public String myFunction(String abc);

Mockito可以帮助返回该方法收到的相同字符串吗?


杨魅力
浏览 323回答 3
3回答

12345678_0001

您可以在Mockito中创建答案。假设我们有一个名为Application的接口,该接口带有方法myFunction。public interface Application {&nbsp; public String myFunction(String abc);}这是带有Mockito答案的测试方法:public void testMyFunction() throws Exception {&nbsp; Application mock = mock(Application.class);&nbsp; when(mock.myFunction(anyString())).thenAnswer(new Answer<String>() {&nbsp; &nbsp; @Override&nbsp; &nbsp; public String answer(InvocationOnMock invocation) throws Throwable {&nbsp; &nbsp; &nbsp; Object[] args = invocation.getArguments();&nbsp; &nbsp; &nbsp; return (String) args[0];&nbsp; &nbsp; }&nbsp; });&nbsp; assertEquals("someString",mock.myFunction("someString"));&nbsp; assertEquals("anotherString",mock.myFunction("anotherString"));}从Mockito 1.9.5和Java 8开始,使用lambda函数提供了一种更简单的方法:when(myMock.myFunction(anyString())).thenAnswer(i -> i.getArguments()[0]);

至尊宝的传说

我有一个非常类似的问题。目的是模拟一个持久化对象并可以按其名称返回的服务。该服务如下所示:public class RoomService {&nbsp; &nbsp; public Room findByName(String roomName) {...}&nbsp; &nbsp; public void persist(Room room) {...}}服务模拟使用地图存储Room实例。RoomService roomService = mock(RoomService.class);final Map<String, Room> roomMap = new HashMap<String, Room>();// mock for method persistdoAnswer(new Answer<Void>() {&nbsp; &nbsp; @Override&nbsp; &nbsp; public Void answer(InvocationOnMock invocation) throws Throwable {&nbsp; &nbsp; &nbsp; &nbsp; Object[] arguments = invocation.getArguments();&nbsp; &nbsp; &nbsp; &nbsp; if (arguments != null && arguments.length > 0 && arguments[0] != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Room room = (Room) arguments[0];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; roomMap.put(room.getName(), room);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; }}).when(roomService).persist(any(Room.class));// mock for method findByNamewhen(roomService.findByName(anyString())).thenAnswer(new Answer<Room>() {&nbsp; &nbsp; @Override&nbsp; &nbsp; public Room answer(InvocationOnMock invocation) throws Throwable {&nbsp; &nbsp; &nbsp; &nbsp; Object[] arguments = invocation.getArguments();&nbsp; &nbsp; &nbsp; &nbsp; if (arguments != null && arguments.length > 0 && arguments[0] != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String key = (String) arguments[0];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (roomMap.containsKey(key)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return roomMap.get(key);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; }});现在,我们可以在此模拟上运行测试。例如:String name = "room";Room room = new Room(name);roomService.persist(room);assertThat(roomService.findByName(name), equalTo(room));assertNull(roomService.findByName("none"));
随时随地看视频慕课网APP

相关分类

Java
我要回答