lundi 18 mars 2019

How to test a call to external api in Spring Boot

I have a method in the service class that uses an external wrapper to call the slack api. The wrapper I'm using is this one if it makes any difference. This is how I'm using the wrapper,

//This is the method in my service class
public String sendMess(SlackObj obj) {
    //SlackObj contains the channel url, channel name and the message
    //build the payload from the SlackObj
    //Slack is the name of the wrapper's class that I'm using
    Slack slack = Slack.getInstance();
    //slack.send is the method that sends the message to slack
    WebhookResponse res = slack.send(url, payload);
    //other logic
}

//This is what I've tried
@Test
public void slackSendMessageTest(){
    //build the slack obj and payload
    //build the mock WebhookResponse
    Slack slackMock = mock(Slack.class)
    when(slackMock.send(channelUrl, payload)).thenReturn(mockWebHookRes);
    assertEquals("SUCCESS", testService.sendMessage(testSlackObj);
}

I am trying to write some tests for this method, so my question is, how would i test it without having the message sent every time I run the test? I believe the cause of this is because slack itself is not mocked and I have no idea as how to inject the mock into the mocked service class.

I am open to refactoring the service class if it helps with the testing. Any suggestions and recommendation is appreciated. Thanks.

Aucun commentaire:

Enregistrer un commentaire