kaviya .P
kaviya .P

Reputation: 479

Mocking of Resttemplate failed in spring boot junit

I am writing junit test cases for the method which is call an rest api,following is the code I have tried:

@RunWith(MockitoJUnitRunner.class)
public class NotificationApiClientTests {

    @Mock
    private RestTemplate restTemplate;

    @InjectMocks
    private NotificationApiClient notificationApiClient;



    @Before
    public void setUp() throws Exception {
          MockitoAnnotations.initMocks(this);
          ReflectionTestUtils.setField(notificationApiClient, "notificationUrl", "myURL***");

    }    

@Test
    public void test_NotificationClickAPI_Call() throws JsonParseException, JsonMappingException, IOException {
        ResponseEntity<NotificationClickEvent[]> notificationClickEventList = util.getValidNotificationEvent_ResponseEntity();

        Mockito.when(restTemplate.exchange(
                Matchers.anyString(), 
                Matchers.any(HttpMethod.class),
                Matchers.<HttpEntity<?>> any(), 
                Matchers.<Class<NotificationClickEvent[]>> any()
                                  )
                                 ).thenReturn(notificationClickEventList);


        NotificationClickEvent[] notificationArray  = notificationApiClient.requestNotificationClick(Const.NotificationClick, "2018-07-31-10");
        assertTrue(notificationArray.length>0);
    }
}

and in My NotificationApiClient , it was:

@Value("${notification.base.url}")
    private String notificationUrl;

    public NotificationApiClient() {
    }

    public UserInfoEvent[] requestUserInfo(String eventType, String dateStr) {
        HttpEntity request = new HttpEntity(setHttpHeaders());
        ResponseEntity<UserInfoEvent[]> response = this.exchange(
                notificationUrl + eventType + "&dateStr=" + dateStr,
                HttpMethod.GET, request, UserInfoEvent[].class);
        UserInfoEvent[] userInfoRequest = response.getBody();
        return userInfoRequest;
    }

but it's not working, as per my code whenever the resttemplate.exchange method is called it should return the notificationClickEventList, But its calling the real api and returns the api result as the list. Can anyone please help me to solve it?

Upvotes: 1

Views: 1576

Answers (1)

In your code you are not using restTemplate.exchange method, It seems you are using notificationApiClient's exchange method. So try this.

@Spy
@InjectMocks
private NotificationApiClient notificationApiClient;


Mockito.when(notificationApiClient.exchange(
            Matchers.anyString(), 
            Matchers.any(HttpMethod.class),
            Matchers.<HttpEntity<?>> any(), 
            Matchers.<Class<NotificationClickEvent[]>> any()
                              )
                             ).thenReturn(notificationClickEventList);

Upvotes: 1

Related Questions