Reputation: 2676
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?
Upvotes: 9
Views: 8434
Reputation: 86
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();
Upvotes: 7