I am expanding upon the basic Spring Boot examples, adding an "autowired" repository dependency to my controller. I would like to modify the unit tests to inject a Mockito mock for that dependency, but I am not sure how.
I was expecting that I could do something like this:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MockServletContext.class)
@WebAppConfiguration
public class ExampleControllerTest {
private MockMvc mvc;
@InjectMocks
ExampleController exampleController;
@Mock
ExampleRepository mockExampleRepository;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mvc = MockMvcBuilders.standaloneSetup(new ExampleController()).build();
}
@Test
public void getExamples_initially_shouldReturnEmptyList() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/example").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("[]")));
}
}
but it doesn't inject the mock into the MockMvc
. Can anyone explain how to do this with @Autowired
dependencies, rather than constructor arguments?
It is because the autowired component requires an special treatment to be “mocked”. This will initialize the application context, but, if your goal is not a integration test, maybe this is unnecessary, because now, you'll have a test case with all dependencies of your project loaded (slow test!).
We can use the @MockBean to add mock objects to the Spring application context. The mock will replace any existing bean of the same type in the application context. If no bean of the same type is defined, a new one will be added.
standaloneSetup() allows to register one or more controllers without the need to use the full WebApplicationContext . @Test public void testHomePage() throws Exception { this.mockMvc.perform(get("/")) .andExpect(status().isOk()) .andExpect(view().name("index")) .andDo(MockMvcResultHandlers.print()); }
Please use @RunWith(MockitoJUnitRunner.class)
instead of @RunWith(SpringJUnit4ClassRunner.class)
and you have to use the ExampleController exampleController;
field with the injected mocks instead of creating a new one in line mvc = MockMvcBuilders.standaloneSetup(new ExampleController()).build();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With