Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock autowired dependencies in Spring Boot MockMvc Unit tests?

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?

like image 818
Don Subert Avatar asked May 26 '16 06:05

Don Subert


People also ask

Can we mock Autowired object?

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!).

What is the difference between @mock and @MockBean?

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.

What is MockMvc standaloneSetup?

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()); }


1 Answers

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();

like image 53
Christian K. Avatar answered Sep 22 '22 06:09

Christian K.