I want to mock a resttemplate.exchange() method but it is not getting mocked . It is throwing NoClassDefFoundError
Here's the class I want to mock:
public class userHelper {
/*
*/
public getUserResponse(userPayload){
String url = "abc/def";
HttpHeaders headers = new HttpHeaders();
headers.setAccept(...);
...
...
HttpEntity<userPayload> httpEntity = new HttpEntity<~>(userpayload,headers);
RestTtemplate restTemplate = new RestTemplate();
restTemplate.getInterceptors().add(testInterceptor.Builder.of().setHttpRequestContext(false).setPrintResponseBody(false).build());
ResponseEntity<userPayload> response = restTemplate.exchange(url,HttpMethod.POST,httpEntity,UserPayload.class);
...
...
...
}
}
In my test class i have mocked the resttemplate but it is not working Test class:
@ExtendWIth(MockitoExtension.class)
public class userHelperTest(){
@Mock
RestTemplate restTemplate;
@Test
getUserResponseTest(){
...
...
when(restTemplate.exchange(ArgumentMatchers.anyString(), ArgumentMatchers.eq(HttpMethod.POST, ArgumentMatchers,any(HttpEntity.class), ArgumentMatchers.eq(UserPayload.class))).thenReturn(response);
}}
Please suggest how to resolve this. Thanks in advance!
CodePudding user response:
The class you are testing should be a Spring Component (or sub-interface i.e. Service). Then you need to have the Mock as a class variable that you can mock somewhere. This means that you need to define the RestTemplate
in a config somewhere.
The config:
@SpringBootApplication
public class YourAppName {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate
}
...
}
The Class in test:
@Service
public class UserHelper {
private RestTemplate restTemplate;
public UserHelper(RestTemplate restTemplate) {
this.restTemplate = restTemplate
}
...
// your methods but remove RetTemplate from them
}
Test:
@SpringBootTest
public class UserHelperTest{
@Mock
RestTemplate restTemplate;
@Autowired // or create it in a @BeforeEach method
UserHelper instanceToTest;
// your test with mocking should now work here
}
CodePudding user response:
In order to mock an object via Mockito, you need to be sure to autowire it and inject the dummy instance into your service method, if you use one. Here's an example:
public class userHelper {
@Autowired
RestTemplate restTemplate;
...
RestTemplate restTemplate = new RestTemplate();
...
And your test class would look like this:
@ExtendWIth(MockitoExtension.class)
public class userHelperTest(){
@Mock
RestTemplate restTemplate;
@InjectMocks
UserHelper userHelper = new UserHelper();
@Test
getUserResponseTest(){
...
This link provides a good explanation: baeldung.com/spring-mock-rest-template