• <i id='CkvwI'><tr id='CkvwI'><dt id='CkvwI'><q id='CkvwI'><span id='CkvwI'><b id='CkvwI'><form id='CkvwI'><ins id='CkvwI'></ins><ul id='CkvwI'></ul><sub id='CkvwI'></sub></form><legend id='CkvwI'></legend><bdo id='CkvwI'><pre id='CkvwI'><center id='CkvwI'></center></pre></bdo></b><th id='CkvwI'></th></span></q></dt></tr></i><div id='CkvwI'><tfoot id='CkvwI'></tfoot><dl id='CkvwI'><fieldset id='CkvwI'></fieldset></dl></div>
  • <legend id='CkvwI'><style id='CkvwI'><dir id='CkvwI'><q id='CkvwI'></q></dir></style></legend>
      <bdo id='CkvwI'></bdo><ul id='CkvwI'></ul>
  • <tfoot id='CkvwI'></tfoot>

        <small id='CkvwI'></small><noframes id='CkvwI'>

      1. 如何使用 Mockito 测试 DAO 方法?

        How to test DAO methods using Mockito?(如何使用 Mockito 测试 DAO 方法?)
        <legend id='bXbdz'><style id='bXbdz'><dir id='bXbdz'><q id='bXbdz'></q></dir></style></legend>

          • <bdo id='bXbdz'></bdo><ul id='bXbdz'></ul>
            <i id='bXbdz'><tr id='bXbdz'><dt id='bXbdz'><q id='bXbdz'><span id='bXbdz'><b id='bXbdz'><form id='bXbdz'><ins id='bXbdz'></ins><ul id='bXbdz'></ul><sub id='bXbdz'></sub></form><legend id='bXbdz'></legend><bdo id='bXbdz'><pre id='bXbdz'><center id='bXbdz'></center></pre></bdo></b><th id='bXbdz'></th></span></q></dt></tr></i><div id='bXbdz'><tfoot id='bXbdz'></tfoot><dl id='bXbdz'><fieldset id='bXbdz'></fieldset></dl></div>

              • <small id='bXbdz'></small><noframes id='bXbdz'>

                <tfoot id='bXbdz'></tfoot>

                    <tbody id='bXbdz'></tbody>
                  本文介绍了如何使用 Mockito 测试 DAO 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                  问题描述

                  我已经开始发现 Mockito 库,但有一个问题我没有找到正确的答案.

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

                  如果我的 UserDAO 类中有这样的方法,可以将用户保存在数据库中:

                  If I have for example such method in my UserDAO class that saves user in database:

                  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 模拟、Connection 模拟、ResultSet 模拟等吗?所以不测试数据库本身?

                  If I want to test for example a DAO class then I need to create a DataSource mock, Connection mock, ResultSet mock etc ? And so not to test the database itself ?

                  但是如果我还想测试 dao 和 database 的行为呢?

                  But what if I want to also test the behavior of dao and database ?

                  您能否提供一些可能有用的代码示例、链接并展示最佳方法?

                  Would you please produce some code samples, links that could be helpful and show best approaches of doing it ?

                  推荐答案

                  这是使用 Mockito 测试您的 UserDAO 的良好开端.此代码使用了大量的 Mockito 功能,因此您可以了解如何使用它们.如果您有任何问题,请告诉我.

                  Here is a good start using Mockito to test your UserDAO. This code uses a good amount of the Mockito features, so you can see how to use them. Let me know if you have questions.

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

                  这篇关于如何使用 Mockito 测试 DAO 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                  相关文档推荐

                  How can I detect integer overflow on 32 bits int?(如何检测 32 位 int 上的整数溢出?)
                  Local variables before return statements, does it matter?(return 语句之前的局部变量,这有关系吗?)
                  How to convert Integer to int?(如何将整数转换为整数?)
                  How do I create an int array with randomly shuffled numbers in a given range(如何在给定范围内创建一个随机打乱数字的 int 数组)
                  Inconsistent behavior on java#39;s ==(java的行为不一致==)
                  Why is Java able to store 0xff000000 as an int?(为什么 Java 能够将 0xff000000 存储为 int?)
                  <tfoot id='z89qC'></tfoot>
                  • <legend id='z89qC'><style id='z89qC'><dir id='z89qC'><q id='z89qC'></q></dir></style></legend>
                      <tbody id='z89qC'></tbody>

                        • <small id='z89qC'></small><noframes id='z89qC'>

                          • <bdo id='z89qC'></bdo><ul id='z89qC'></ul>
                            <i id='z89qC'><tr id='z89qC'><dt id='z89qC'><q id='z89qC'><span id='z89qC'><b id='z89qC'><form id='z89qC'><ins id='z89qC'></ins><ul id='z89qC'></ul><sub id='z89qC'></sub></form><legend id='z89qC'></legend><bdo id='z89qC'><pre id='z89qC'><center id='z89qC'></center></pre></bdo></b><th id='z89qC'></th></span></q></dt></tr></i><div id='z89qC'><tfoot id='z89qC'></tfoot><dl id='z89qC'><fieldset id='z89qC'></fieldset></dl></div>