i have service method resttemplate. part of unit test, trying mock how failing.
service method:
@autowired private resttemplate getresttemplate; return getresttemplate.getforobject(restdiagnosisgeturl, sfdccustomerresponsetype.class);
test method:
private carestosfdcresponseconverter carestosfdcresponseconverter; @before public void setup() throws exception { carestosfdcresponseconverter = new carestosfdcresponseconverter(); } @test public void testconvert(){ resttemplate mock = mockito.mock(resttemplate.class); mockito.when(mock.getforobject(matchers.anystring(), matchers.eq(sfdccustomerresponsetype.class))).thenreturn(sfdccustomerresponsetype); } sfdcrequest = carestosfdcresponseconverter.convert(responseforsfdcandhybris);
it giving nullpointerexception. looks failing mock rest template , breaking there rest template null. appreciated.thanks
it's not failing mock rest template, it's not injecting mocked rest template production class. there @ least 2 ways fix this.
you can change production code , use constructor injection. move resttemplate constructor parameter , can pass mock in test:
@service public class myservice { @autowired public myservice(resttemplate resttemplate) { this.resttemplate = resttemplate; } }
in test create service other object , pass mocked rest template.
or can change test inject service using following annotation:
@runwith(mockitojunitrunner.class) public class myservicetest { @injectmocks private myservice myservice; @mock private resttemplate resttemplate; @test public void testconvert(){ mockito.when(mock.getforobject(matchers.anystring(), matchers.eq(sfdccustomerresponsetype.class))).thenreturn(sfdccustomerresponsetype); } }
you can see example in question: using @mock , @injectmocks
i prefer constructor injection.
Comments
Post a Comment