Как я могу смоделировать сервис со сложным запросом в Mockito и JUint? - PullRequest
0 голосов
/ 11 апреля 2019

У меня есть интерфейс:

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. Как я могу издеваться над этим?

1 Ответ

2 голосов
/ 11 апреля 2019

Попробуйте это:

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