Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why mockMVC and mockito don't work together?

I have restful services and I want to unit test them without connecting to database, therefore I have written this piece of code:

@Before
public void setup() throws Exception {
    this.mockMvc = webAppContextSetup(webApplicationContext).build();

    adminDao = mock(AdminDaoImpl.class);
    adminService = new AdminServiceImpl(adminDao);
}

@Test
public void getUserList_test() throws Exception {
    User user = getTestUser();
    List<User> expected = spy(Lists.newArrayList(user));

    when(adminDao.selectUserList()).thenReturn(expected);


    mockMvc.perform(get("/admin/user"))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$", hasSize(1)))
        ;           
}

The service gets called but my problem is this line of code

when(adminDao.selectUserList()).thenReturn(expected);

is not working, I mean it really calls the adminDao.select method and therefore gets the result from database. which I don't want. Do you have any idea how can I mock the method call?

like image 386
Shilan Avatar asked Apr 28 '16 11:04

Shilan


2 Answers

Thanks to @M. Deinum, I fixed my problem, I added a TestContext configuration file:

@Configuration
public class TestContext {

@Bean
public AdminDaoImpl adminDao() {
    return Mockito.mock(AdminDaoImpl.class);
}

@Bean
public AdminServiceImpl adminService() {
    return new AdminServiceImpl(adminDao());
}       
}

and then in my test class I annotated the class with

@ContextConfiguration(classes = {TestContext.class})

worth to mention in setUp of the test class I need to reset the mockedClass to prevent leakage:

@Before
public void setup() throws Exception {
    Mockito.reset(adminDaoMock);

    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
like image 60
Shilan Avatar answered Sep 28 '22 01:09

Shilan


Instead of creating a separate TestContext class use @MockBean annotation for the same.

 @MockBean
 AdminDao adminDao;

And then use it as per your need.

 @Test
public void getUserList_test() throws Exception {
   User user = getTestUser();
   List<User> expected = spy(Lists.newArrayList(user));

   when(adminDao.selectUserList()).thenReturn(expected);


   mockMvc.perform(get("/admin/user"))
    .andExpect(status().isOk())
    .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
    .andExpect(jsonPath("$", hasSize(1)))
    ;           
}
like image 32
Deepak Goel Avatar answered Sep 28 '22 00:09

Deepak Goel