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

标签 java unit-testing junit mocking mockito

我有一个界面:

public interface SenderService {
    String send(long amount);
}

我有这个接口(interface)的实现:

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

现在我想为此服务编写单元测试。我需要模拟 ThirdPartyService 的方法 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 中创建。我怎样才能 mock 它?

最佳答案

试试这个:

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

关于java - 如何在 Mockito 和 JUnit 中模拟具有复杂请求的服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55633287/

相关文章:

java - java中的用户界面

Java ResultSet 复制到通用对象或列表

具有所有键的单字节 [] 数组的 Java hashmap

javascript - 如何导入 `isOneline`函数?

java - 如何使用不同的 spring 上下文为 junit 集成测试创建同一对象的多个实例?

java - Travis、Maven 和 github 的 Sonarcloud 失败

比较数组的 C 单元测试框架

python - 单元测试测试套件

java - 只有一个有效的测试用例,我可以节省编写失败测试用例的时间吗? (我可以自动生成它们吗)

java - 创建 ANT 脚本以在 Tavis-CI 上构建并在提交时运行 JUnit 测试