DAO method is not being mocked

NaN :

I have a UserDAO that has methods like add,delete,update,getUser and getUsers (to manipulate my database). I also have a Requestmapping that I want to test via Mockito. Here is everything relevant in terms of what I have:

The test:

@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(value = UserController.class)
public class UserControllerTest
{

@Autowired
private MockMvc mockMvc;

@Mock
private UserDAO userDao;

@InjectMocks
private UserController userController;

@Before
public void setUp()
{
    MockitoAnnotations.initMocks(this);
    mockMvc = MockMvcBuilders
            .standaloneSetup(userController)
            .build();
}

@Test
public void testGetAllUsersSuccess() throws Exception{
    User s = new User();
    List<User> users = Arrays.asList(
            new User(1,"somebody", "pass", "[email protected]"),
            new User(2, "sam", "mypass", "[email protected]"));

    doReturn(users).when(userDao).getUsers();

    mockMvc.perform(get("/userList"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(jsonPath("$", hasSize(2)))
            .andExpect(jsonPath("$[0].userID", is(1)))
            .andExpect(jsonPath("$[0].name", is("somebody")))
            .andExpect(jsonPath("$[0].password", is("pass")))
            .andExpect(jsonPath("$[0].email", is("[email protected]")))
            .andExpect(jsonPath("$[1].userID", is(2)))
            .andExpect(jsonPath("$[1].name", is("sam")))
            .andExpect(jsonPath("$[1].password", is("mypass")))
            .andExpect(jsonPath("$[1].email", is("[email protected]")));

        verify(userDao, times(1)).getUsers();
        verifyNoMoreInteractions(userDao);
    }
}

UserController where I have my requestmapping:

@RestController
public class UserController {
    /**
     *
     *
     * @return list of all users
     */
    @RequestMapping(value = "/userList", method = RequestMethod.GET)
    public List<User> user() throws Exception {
        UserDAO gettingUsers = new UserDAO();
        return gettingUsers.getUsers();
    }

}

the getUsers() method:

public List<User> getUsers(){
    try(Session session = HibernateUtil.getSessionFactory().openSession()){
        return session.createQuery("from User", User.class).getResultList();
    }
}

PROBLEM: When I execute my test, a connection is made with the database (which is not what I want) instead of a fake instance of UserDAO that only returns the users list that I have made in mockito.

QUESTION: What should my code look like to be able to mock the userDAO method getUsers() such that it doesn't return the users from the database but instead returns the faked users list when I call it by requesting the get method of "/userList"?

UPDATE=

SOLUTION:

My new Controller:

@RestController
public class UserController {

private UserDAO userDAO;

public UserController (UserDAO userDAO)
{
    this.userDAO = userDAO;
}

/**
 *
 *
 * @return list of all users
 */
@GetMapping(value = "/Users", method = RequestMethod.GET)
public List<User> users() throws Exception {
    return userDAO.getUsers();
}

}

Changes done in test:

//...
@MockBean
private UserDAO userDao;
....
when(userDao.getUsers()).thenReturn(users);
...//

Spring didn't find my userDAO Bean so I added the package name where I stored the bean in the ApplicationConfiguration class of mine. Doing this, Spring was able to inject the bean in the constructor.

davidxxx :

The userDao mock is never set to the controller under test.

1) You don't want to use new to instantiate the UserDAO in your Controller :

 UserDAO gettingUsers = new UserDAO();

You want to inject it as a Spring Bean.
Besides you also have to make the dependency visible because actually it is not settable from the unit test POV.

You could inject it in the constructor :

private UserDAO userDAO;
public UserController (UserDAO userDAO){
  this.userDAO = userDAO;
}

2) You mock Spring bean in a running container with @MockBean from Spring Boot test not with @Mock from Mockito.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=159719&siteId=1