Given an autowired item inside a test running with the SpringJUnit4ClassRunner follow this simple syntax.
Instead of the Mockito.any, is possible to insert directly the value of the object.
@Autowired private RestOperations restTemplate; @Test private void testSomething() { ... Mockito.when(restTemplate.postForObject( Mockito.any(String.class), Mockito.any(Map.class), Mockito.any(Class.class) )).thenReturn(response); }
The matchers can be used also to verify if the method was called (as the calls on autowired)
@Test private void testSomething() { ... verify(restTemplate, times(1)).postForObject( Mockito.any(String.class), Mockito.any(Map.class), Mockito.any(Class.class)); }
The matchers can be expressed in various ways. In case a matcher should match a template based value, then the square brackets syntax should be used!!
Mockito.any(String.class); Mockito.<String>any(); Mockito.anyString(); Mockito.anyInt();
To match for equality differences, etc
Mockito.eq("Value to verify against");
The specific item that had been mocked can be resetted to initial state
@Autowired private RestOperations restTemplate; @Before public void initializeTarget() { ... Mockito.reset(restTemplate); }
It is possible to use the autowired annotation as with spring. This is for SpringBoot & Spring 4.
//run with Spring context @RunWith(SpringJUnit4ClassRunner.class) //load the configuration through the standard spring boot application class @SpringApplicationConfiguration(classes = LvmConfigurationServiceApplication.class) public class AlarmConfigServiceTest { //This object (not an interface) is the target of our tests. //It will be filled by Spring @Autowired //the mocks will be injected automatically in it. @InjectMocks private AlarmConfigService target; //This class will be mocked @Mock private QueryTemplateService queryTemplate; //This method will reset and initalize all mocks for //each test run @Before public void setupTarget() { MockitoAnnotations.initMocks(this); } @Test public void doTest() { // .... } }