'How To Test Login Method In JUnit?

I have been using white box testing with JUnit to test some methods that I have in my DAO Implementation class. I am trying to test the login functionality, which is defined in the Service Implementation class. This is how the method looks like.

    public Message login(String userName, String password) {
        String result;
        String state;
        UserDAO dao = new UserDAOImpl();
        User user = null;
        try {
            user = dao.findUser(userName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (user != null){
            if (!password.equals(user.getPassword())){
                state = WRONG;
                result = Constant.Item.PASSWORD + Constant.Operation.IS + Constant.State.WRONG;
            }else{
                state = SUCCESS;
                result = Constant.Item.USER + Constant.Operation.LOGIN + SUCCESS;
            }
        }else {
            state = NOT_EXIST;
            result = Constant.Item.USER + Constant.Operation.IS + Constant.State.NOT_EXIST;
        }
        Message message = new Message();
        message.setState(state);
        message.setDetail(result);
        message.setData(user);
        return message;
    }

` How can I test this method in JUnit?



Solution 1:[1]

You would want to use Mocking to properly test this.

First thing I'd say is that you might want to look at instantiating your DAO outside of your method as it's not very testable right now.

After that you'd want to mock your UserDAOImpl and pass that into your class constructor where login method is.

With mockito you'd need to mock your DAO and specify the object to return when a particular method is called

UserDAOImpl dao = Mockito.mock(UserDAOImpl.class);
Mockito.when(dao.findUser("testValueHere")).thenReturn(mockedUserObjectHere)

This gives you a good starting spot but you'd need to dig through mockito samples to understand and perhaps the docs https://site.mockito.org/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 andresmonc