如何在Mockito和JUint中模拟具有复杂请求的服务?

时间:2019-04-11 13:09:49

标签: java unit-testing junit mocking mockito

我有一个界面:

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);

    }
}

ThirdPartyRequestSenderServiceAdapter中创建。我该如何嘲笑它?

1 个答案:

答案 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));