Pandit Biradar
Pandit Biradar

Reputation: 1877

Mockito mock is giving null for given test cases

I am using the SpringRunner to run the Junit mockito test case , below is the class , i was trying to write the test case , but getting null object

    public class AccountManager {

        public String getToken() throws Exception {
               @Autowired
               RestClient restClient;

                String auth = apiUserPrefix + apiUserName + BatchJobConstants.COLON + apiUserPassword;
                byte[] encodedAuth = Base64.encodeBase64(
                        auth.getBytes(StandardCharsets.UTF_8));
                String authHeader = BatchJobConstants.BASIC_SPACE + new String(encodedAuth);
                String token= null;
                MultiValueMap<String, String> data = new LinkedMultiValueMap<>();
                data.add("grant_type", "client_credential");
                String accManagerUrl = accManagerHost+":"+accManagerPort+"/"+accManagerResPath;
                RestResponseObject responseObject = null;

                try {
                    responseObject = restClient.execute(accManagerUrl, HttpMethod.POST, data, String.class, authHeader);
                    if (responseObject != null && responseObject.getPayload() != null && responseObject.getStatusCode() == HttpStatus.OK) {
                        JsonElement responseJson = (JsonElement) responseObject.getPayload();
                        if (responseJson.isJsonObject()) {
                            token= responseJson.getAsJsonObject().get(BatchJobConstants.ACCESS_TOKEN).getAsString();
                        }catch(RunTimeException e) {
//e
}
    return token;
        }

//Junit test case

@RunWith(SpringRunner.class)
    public class AccountManagerTest {
    @InjectMocks
        AccountManager accountManager;
    @Mock
         RestClient restClient;
 @Test
    public void getTokenAccMgrSucess() throws Exception {
        RestResponseObject restResponseObject = Mockito.mock(RestResponseObject.class);

        Mockito.when(restClient.execute(Mockito.anyString(), Mockito.any(HttpMethod.class),
                Mockito.anyString(), Mockito.eq(String.class), Mockito.anyString())).thenReturn(restResponseObject);
        String token = accountManagerTokenProvider.getToken();
        Assert.assertEquals("Token value {} ", null, token);

    }

    }

But still the below code return null value even after mocking this, can you please help how to mock this.

responseObject = restClient.execute(accManagerUrl, HttpMethod.POST, data, String.class, authHeader);

Note: Only Mockito needs to use no powermockito

Upvotes: 0

Views: 2788

Answers (2)

Pandit Biradar
Pandit Biradar

Reputation: 1877

Finally worked with mockito only just user any() instead of anyString(), since the Object is not matching with string only

Mockito.when(restClient.execute(Mockito.any(), Mockito.any(HttpMethod.class),
                Mockito.any(), Mockito.eq(String.class), Mockito.any())).thenReturn(restResponseObject);

Upvotes: 1

beatrice
beatrice

Reputation: 4401

For Autowired fields you not only have to mock it but should bind the mocked class to the spring context. You have two options :

1. Mark the mocked class as primary bean

@Configuration
    public class TestConfiguration {
        @Bean
        @Primary
        public RestClient restClient() {
            return Mockito.mock(RestClient.class);
        }
    }

2.Use @MockBean annotation

 @MockBean
 RestClient restClient;

More on this :
https://www.baeldung.com/injecting-mocks-in-spring
https://www.baeldung.com/java-spring-mockito-mock-mockbean

Upvotes: 1

Related Questions