我有一个界面:
public interface SenderService {
String send(long amount);
}
我有一个此接口的实现:
public class SenderServiceAdapter implements SenderService {
private final ThirdPartyService thirdPartyService;
public SenderServiceAdapter(ThirdPartyService thirdPartyService) {
this.thirdPartyService = thirdPartyService;
}
@Override
public String send(long amount) {
ThirdPartyRequest thirdPartyRequest = new ThirdPartyRequest();
thirdPartyRequest.setAmount(amount);
thirdPartyRequest.setId(UUID.randomUUID().toString());
thirdPartyRequest.setDate(new Date());
ThirdPartyResponse thirdPartyResponse = thirdPartyService.send(thirdPartyRequest);
String status = thirdPartyResponse.getStatus();
if (status.equals("Error")) throw new RuntimeException("blablabla");
return thirdPartyResponse.getMessage();
}
}
现在,我要为此服务写Unit test
。我需要模拟thirdPartyService's
方法send
。但是我不知道如何。
public class SenderServiceAdapterTest {
private ThirdPartyService thirdPartyService;
private SenderService senderService;
@Before
public void setUp() throws Exception {
thirdPartyService = Mockito.mock(ThirdPartyService.class);
senderService = new SenderServiceAdapter(thirdPartyService);
}
@Test
public void send() {
when(thirdPartyService.send(new ThirdPartyRequest())).thenReturn(new ThirdPartyResponse());
String message = senderService.send(100L);
}
}
ThirdPartyRequest
在SenderServiceAdapter
中创建。我该如何嘲笑它?
答案 0 :(得分:2)
尝试一下:
doReturn(new ThirdPartyResponse()).when(thirdPartyService).send(any(ThirdPartyRequest.class));
另外,通过查看代码,您需要在响应中进行设置,所以您必须这样做:
ThirdPartyResponse response = new ThirdPartyResponse(); //or mock
response.setStatus(...);
response.setMessage(...);
doReturn(response).when(thirdPartyService).send(any(ThirdPartyRequest.class));