簡體   English   中英

使用連接池對帶有 JUnit 的 DAO 類進行單元測試

[英]Unit test DAO classes with JUnit using a Connection Pool

大家好,我是新來的,我需要您的幫助來使用 junit 和帶有連接池的 DAO class 進行單元測試。 這是 ConPool:

public class ConPool {

private static DataSource datasource;

/**
 * {@return} Connection
 * {@throws} SQLException
 *     Ritorna la connessione al db.
 */

public static Connection getConnection() throws SQLException {
if (datasource == null) {
  PoolProperties p = new PoolProperties();
  p.setUrl("jdbc:mysql://localhost:3306/GameLand?serverTimezone="
          + TimeZone.getDefault().getID());
  p.setDriverClassName("com.mysql.cj.jdbc.Driver");
  p.setUsername("root");
  p.setPassword("basedidati");
  p.setMaxActive(100);
  p.setInitialSize(10);
  p.setMinIdle(10);
  p.setRemoveAbandonedTimeout(60);
  p.setRemoveAbandoned(true);
  datasource = new DataSource();
  datasource.setPoolProperties(p);
}
  return datasource.getConnection();
 }
}

這是我要測試的DAO class:

public class OrdineDAO {
/**
 * {@return} ArrayList of Ordine.
 */

public synchronized ArrayList<Ordine> doRetrieveAll() {

String query = "SELECT * FROM ordine";
ArrayList<Ordine> result = new ArrayList<Ordine>();

try (Connection conn = ConPool.getConnection()) {

  PreparedStatement ps = conn.prepareStatement(query);
  ResultSet rs = ps.executeQuery();
  while (rs.next()) {

    Ordine ord = new Ordine();
    ord.setConsegnato(rs.getBoolean("consegnato"));
    ord.setDataOra(rs.getString("dataOra"));
    ord.setIdOrdine(rs.getInt("idOrdine"));
    ord.setIdProdotto(rs.getInt("idProdotto"));
    ord.setPrezzoFis(rs.getDouble("prezzoFis"));
    ord.setPrezzoDig(rs.getDouble("prezzoDig"));
    ord.setIva(rs.getDouble("iva"));
    ord.setQuantitaDigitale(rs.getInt("quantitaDigitale"));
    ord.setQuantitaFisico(rs.getInt("quantitaFisico"));
    ord.setIdUtente(rs.getInt("idUtente"));
    result.add(ord);

  }

} catch (SQLException e) {

  e.printStackTrace();

}


return result;
}
/**
 * {@param} id: int.
 * {@return} ArrayList of Ordine.
 */

public synchronized ArrayList<Ordine> doRetrieveByUser(int id) {

PreparedStatement ps = null;
String query = "SELECT * FROM ordine WHERE idUtente = ?";
ArrayList<Ordine> result = new ArrayList<Ordine>();

try (Connection conn = ConPool.getConnection()) {

  ps = conn.prepareStatement(query);
  ps.setInt(1, id);
  ResultSet rs = ps.executeQuery();
  while (rs.next()) {

    Ordine ord = new Ordine();
    ord.setConsegnato(rs.getBoolean("consegnato"));
    ord.setDataOra(rs.getString("dataOra"));
    ord.setIdOrdine(rs.getInt("idOrdine"));
    ord.setIdProdotto(rs.getInt("idProdotto"));
    ord.setPrezzoFis(rs.getDouble("prezzoFis"));
    ord.setPrezzoDig(rs.getDouble("prezzoDig"));
    ord.setIva(rs.getDouble("iva"));
    ord.setQuantitaDigitale(rs.getInt("quantitaDigitale"));
    ord.setQuantitaFisico(rs.getInt("quantitaFisico"));
    ord.setIdUtente(rs.getInt("idUtente"));
    result.add(ord);

  }

} catch (SQLException e) {

  e.printStackTrace();

}

return result;
}
/**
 * {@param} data1: String.
 * {@param} data2: String.
 * {@return} ArrayList of Ordine.
 */

public synchronized ArrayList<Ordine> doRetrieveByDate(String data1, String data2) {

PreparedStatement ps = null;
String query = "SELECT * FROM ordine WHERE dataOra >= ? AND dataOra <= ?";
ArrayList<Ordine> result = new ArrayList<Ordine>();

try (Connection conn = ConPool.getConnection()) {

  ps = conn.prepareStatement(query);
  ps.setString(1, data1);
  ps.setString(2, data2);
  ResultSet rs = ps.executeQuery();
  while (rs.next()) {

    Ordine ord = new Ordine();
    ord.setConsegnato(rs.getBoolean("consegnato"));
    ord.setDataOra(rs.getString("dataOra"));
    ord.setIdOrdine(rs.getInt("idOrdine"));
    ord.setIdProdotto(rs.getInt("idProdotto"));
    ord.setPrezzoFis(rs.getDouble("prezzoFis"));
    ord.setPrezzoDig(rs.getDouble("prezzoDig"));
    ord.setIva(rs.getDouble("iva"));
    ord.setQuantitaDigitale(rs.getInt("quantitaDigitale"));
    ord.setQuantitaFisico(rs.getInt("quantitaFisico"));
    ord.setIdUtente(rs.getInt("idUtente"));
    result.add(ord);

  }

} catch (SQLException e) {

  e.printStackTrace();

}

 return result;
 }

}

首先從 doRetrieveAll 方法開始,我嘗試做一個

@Test
public void doRetrieveAll_Success() throws SQLException {
    assertNotNull(ordineDAO.doRetrieveAll());
}

但我需要知道如何設置 @BeforeAll 才能測試此方法。 你能幫我理解如何正確設置測試 class 嗎? 謝謝

您可以使用 PowerMockito 來實現這一點。 我提到 PowerMockito 而不是 Mockito 的唯一原因是因為您的getConnection()方法是 static 並且使用 PowerMockito 模擬 static 方法更容易

您需要添加以下依賴項才能使 PowerMockito 正常工作。

    <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-module-junit4</artifactId>
      <version>1.6.4</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-api-mockito</artifactId>
      <version>1.6.4</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-module-junit4-rule</artifactId>
      <version>1.6.4</version>
      <scope>test</scope>
    </dependency>

這是測試方法。

import static org.mockito.Matchers.any;
import static org.powermock.api.mockito.PowerMockito.when;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(ConPool.class)
public class OrdineDAOTest {

  @Mock
  private Connection c;

  @Mock
  private PreparedStatement stmt;

  @Mock
  private ResultSet rs;

  @Test
  public void testDoRetrieveAll() {
    try {
      //Mocking the Static ConPool Class 
      PowerMockito.mockStatic(ConPool.class);
      //Making the ConPool.getConnection() method to return Mocked Connection 
      when(ConPool.getConnection()).thenReturn(c);
      //Making the prepareStatement method to return Mocked PrepareStatement 
      when(c.prepareStatement(any(String.class))).thenReturn(stmt);
      // Mocking the Values in ResultSet 
      when(rs.getInt("idOrdine")).thenReturn(10); 
      //This means result set has only one set of result
      //Mocking rs.next() to return true first and then return false the second time
      when(rs.next()).thenReturn(true).thenReturn(false);
      //Making executeQuery() method to return mocked resultset
      when(stmt.executeQuery()).thenReturn(rs);

      OrdineDAO dao = new OrdineDAO();
      // Invoking the actual method from dao
      ArrayList<Ordine> list = dao.doRetrieveAll();
      //Comparing the expected vs actual
      Assert.assertEquals(1, list.size());
      Assert.assertEquals(10, list.get(0).getIdOrdine());
    } catch (Exception e) {
      e.printStackTrace();
    }

  }
}

我已經用注釋行解釋了代碼。

我已經在 java 8 以及上面提到的依賴項上自己測試了它,一切對我來說都很好。

太好了,它工作正常。 非常感謝。 我還想看看如何使用 mockito 創建這個測試用例。 當我將測試 doRetrieveByUser 和 doRetrieveByDate 時,我不知道是否必須測試成功/失敗場景(傳遞好/錯誤的參數),或者我可以以與 doRetrieveAll 測試用例“相同”的方式編寫這些測試。 希望很清楚。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM