如何使用Mockito测试DAO方法?

vdzxcuhz  于 2022-11-08  发布在  其他
关注(0)|答案(5)|浏览(500)

我已经开始发现Mockito图书馆,有一个问题,我没有找到适当的答案。
例如,如果我的UserDAO类中有这样一个方法,它将用户保存在数据库中:

public class UserDAO{
...
 public void create(User user) {
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet generatedKeys = null;
        try {

            connection = getConnection();
            pstmt = connection.prepareStatement(INSERT_USER,
                    PreparedStatement.RETURN_GENERATED_KEYS);
            int counter = 1;
            pstmt.setString(counter++, user.getFirstName());
            pstmt.setString(counter++, user.getLastName());
            pstmt.setString(counter++, user.getEmail());
            pstmt.setString(counter++, user.getPassword());
            pstmt.setString(counter++, user.getRole());
            pstmt.setString(counter, user.getLang());

            pstmt.execute();
            connection.commit();
            generatedKeys = pstmt.getGeneratedKeys();

            if (generatedKeys.next()) {
                user.setId(generatedKeys.getInt(Fields.GENERATED_KEY));
            }
        } catch (SQLException e) {
            rollback(connection);
            LOG.error("Can not create a user", e);
        } finally {
            close(connection);
            close(pstmt);
            close(generatedKeys);
        }
    }
  ....
}

我该如何测试它?
例如,如果我想测试一个DAO类,那么我需要创建一个DataSource mock,Connection mock,ResultSet mock等?所以不是测试数据库本身吗?
但是如果我也想测试dao和数据库的行为呢?
你能不能提供一些代码样本,链接,这可能是有帮助的,并显示最好的方法这样做?

fnx2tebb

fnx2tebb1#

这是一个使用Mockito测试UserDAO的良好开端。这段代码使用了大量的Mockito特性,因此您可以了解如何使用它们。如果您有问题,请告诉我。

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import org.mockito.Mock;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class TestUserDAO {

    @Mock
    DataSource mockDataSource;
    @Mock
    Connection mockConn;
    @Mock
    PreparedStatement mockPreparedStmnt;
    @Mock
    ResultSet mockResultSet;
    int userId = 100;

    public TestUserDAO() {
    }

    @BeforeClass
    public static void setUpClass() throws Exception {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() throws SQLException {
        when(mockDataSource.getConnection()).thenReturn(mockConn);
        when(mockDataSource.getConnection(anyString(), anyString())).thenReturn(mockConn);
        doNothing().when(mockConn).commit();
        when(mockConn.prepareStatement(anyString(), anyInt())).thenReturn(mockPreparedStmnt);
        doNothing().when(mockPreparedStmnt).setString(anyInt(), anyString());
        when(mockPreparedStmnt.execute()).thenReturn(Boolean.TRUE);
        when(mockPreparedStmnt.getGeneratedKeys()).thenReturn(mockResultSet);
        when(mockResultSet.next()).thenReturn(Boolean.TRUE, Boolean.FALSE);
        when(mockResultSet.getInt(Fields.GENERATED_KEYS)).thenReturn(userId);
    }

    @After
    public void tearDown() {
    }

    @Test
    public void testCreateWithNoExceptions() throws SQLException {

        UserDAO instance = new UserDAO(mockDataSource);
        instance.create(new User());

        //verify and assert
        verify(mockConn, times(1)).prepareStatement(anyString(), anyInt());
        verify(mockPreparedStmnt, times(6)).setString(anyInt(), anyString());
        verify(mockPreparedStmnt, times(1)).execute();
        verify(mockConn, times(1)).commit();
        verify(mockResultSet, times(2)).next();
        verify(mockResultSet, times(1)).getInt(Fields.GENERATED_KEYS);
    }

    @Test(expected = SQLException.class)
    public void testCreateWithPreparedStmntException() throws SQLException {

         //mock
         when(mockConn.prepareStatement(anyString(), anyInt())).thenThrow(new SQLException());

        try {
            UserDAO instance = new UserDAO(mockDataSource);
            instance.create(new User());
        } catch (SQLException se) {
            //verify and assert
            verify(mockConn, times(1)).prepareStatement(anyString(), anyInt());
            verify(mockPreparedStmnt, times(0)).setString(anyInt(), anyString());
            verify(mockPreparedStmnt, times(0)).execute();
            verify(mockConn, times(0)).commit();
            verify(mockResultSet, times(0)).next();
            verify(mockResultSet, times(0)).getInt(Fields.GENERATED_KEYS);
            throw se;
        }

    }
}
uxh89sit

uxh89sit2#

但是如果我也想测试dao和数据库的行为呢?
如果您确实想测试数据库(这是您应该做的!),那就没有办法了--您需要一个实际的数据库。Mockito虽然是一个很棒的库,但可能是不适合这项工作的工具。

6rqinv9w

6rqinv9w3#

下面是您 * 应该 * 测试它的方法:

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

关于上述内容的几点注意事项:
1)测试看起来简短,简单,易于理解,因为 * 他们应该 *;如果它们看起来像另一个答案中的那些又大又丑,那你就犯了根本性的错误。
2)测试代码可以也应该有自己的基础结构帮助器,比如IntegrationTests基类,它将隐藏实际测试中任何讨厌的JDBC/ORM访问。我在几个项目中实现了这样的帮助器,所以我知道这是可以做到的,但这将是其他问题的材料。

ef1yzkbh

ef1yzkbh4#

DBUnit这样的工具结合JUnit可以帮助您使用数据库测试DAO。DBUnit可以帮助您在UnitTest之前将测试数据插入到数据库中,并在测试之后将数据库中的数据与您的预期进行比较。

hs1rzwqc

hs1rzwqc5#

这是我的测验应用程序中的一个示例

@Test
fun quizDao() {
    val database = mockk<AppDatabase>()
    val dao = mockk<QuizDao>()
    val application = mockk<Application>()
    val appModule = mockk<AppModule>()
//quiz
    val quiz1 = Quiz("Joe","Best Quize","people Around the World","General",23)
//Questions
    val questions1 : Questions = Questions(1,"What's your group", "G1","G2","G3","G4","G1")

    every { dao.getQuizQuestions(23) } returns listOf(questions1)

    assertEquals(listOf(questions1),dao.getQuizQuestions(23))

}

}

相关问题