How to test DAO methods using Mockito?

后端 未结 4 640
抹茶落季
抹茶落季 2021-01-31 09:24

I\'ve started to discovered Mockito library and there is a question for which I didn\'t find the proper answer.

If I have for example such method in my UserDAO class tha

4条回答
  •  北海茫月
    2021-01-31 09:43

    Here is how you should test it:

    public class UserDAOTest extends IntegrationTests
    {
        // Or do it in a @Before method, if needed.
        UserDAO dao = new UserDAO();
    
        @Test
        public void createValidUser() {
            User validUser = new User(
                "John", "Smith", "johns@gmail.com", "Abc123!@",
                "admin", "en"); // or use setters as needed
    
            dao.create(validUser);
    
            assertEntityCreatedInDB(validUser);
        }
    
        @Test
        public void attemptToCreateInvalidUser() {
            User invalidUser = new User("", null, null, "", null, "XY");
    
            dao.create(invalidUser);
    
            // This really shouldn't be done this way, as DAOs are not supposed
            // to manage transactions; instead, a suitable, descriptive
            // exception should be thrown by the DAO and checked in the test.
            assertTransactionWasRolledBack();
        }
    }
    

    A couple notes about the above:

    1) The tests look short, simple, and easy to understand, as they should be; if they look big and ugly as those in another answer, you are doing something fundamentally wrong.

    2) Test code can and should have its own infrastructure helpers, such as the IntegrationTests base class, which will hide any nasty JDBC/ORM access from the actual tests. I implemented such helpers in several projects, so I know this can be done, but that would be stuff for other questions.

提交回复
热议问题