I have a class which I am trying unit test. I am trying to test it using Mockito, and to resolve the spring injection with mockito I am using Springockito and Springockito-annotations.
@ContextConfiguration(loader = SpringockitoContextLoader.class,
locations = {"classpath:testApplication-context-EU.xml"})
public class RelatedSearchToHotUrlProcessorTest extends AbstractJUnit4SpringContextTests {
@Autowired
RelatedSearchToHotUrlProcessor processor;
@ReplaceWithMock
private RestOperations restTemplate;
@Test
public void testGetCategoryFromIdWithNoStoredAlias() {
Taxonomy mockTaxonomy = mock(Taxonomy.class, RETURNS_DEEP_STUBS);
GraphType.Node mockNode = mock(GraphType.Node.class);
when(restTemplate.getForObject(anyString(), eq(Taxonomy.class))).thenReturn(mockTaxonomy);
when(mockTaxonomy
.getRev()
.get(0)
.getCountry()
.get(0)
.getGraph()
.getNodeOrAtom()
.get(0)).thenReturn(mockNode);
when(mockNode.getAlias()).thenReturn("mockalias");
String categoryAlias = processor.getCategoryAliasFromId(13130L);
assertEquals("mockalias", categoryAlias);
}
}
If I remove the @ReplaceWithMock
and the private RestOperations restTemplate
lines then it makes the right call and the value can be validated as correct. However, I want to mock the RestOperations object inside the processor, but using the @ReplaceWithMock makes the restTemplate variable null, causing it to fail. I haven't been able to work out how to isolate this member and mock it.