如何为 Dao 类编写 Junit 测试用例?

0 tdd junit clover

这是我的 dao 类,谁能告诉我这个 dao 方法的模式。

public String getProcessNames() throws IOException{
    Gson gson=new Gson();
    JSONObject output=new JSONObject();
    String responseGson;
    Session session = ConnectionDAO.getBoltSession();
    String query = qpObj.getQueryValue("neo4j.processMonitor.getProcessNames");
    StatementResult result = session.run(query);
    JSONArray dataArray= new JSONArray();
    try{
        while ( result.hasNext() )
        {
            Record record = result.next();
            responseGson=gson.toJson(record.asMap());
            JSONObject responseJson=new JSONObject(responseGson);
            dataArray.put(responseJson.get("ProcessName"));
            output.put("results",dataArray);

        }
    }
    catch(Exception e){
        e.printStackTrace();
    }
    finally{
        if(session.isOpen()){
            session.close();
        }
    }
    return output.toString();
}
Run Code Online (Sandbox Code Playgroud)

或者任何人都可以提供直接链接以供参考,这对我有好处。谢谢

Flo*_*etz 5

嗯,关于测试的一件事是它也会带来更好的代码,因为糟糕的代码通常不太可测试。但在此之前,让我们先考虑一个简单的问题:您想测试什么?

a)您可以测试方法本身,而无需连接数据库,这将是一个单元测试

b) 你可以测试方法和数据库结果,这更像是一个集成测试

就我个人而言,我会同时编写单元测试和集成测试,因为两者都有其用途(单元测试更快并且可以更频繁地运行,集成测试将测试更多)。但让我们从单元测试开始......

单元测试的主要问题是......

Session session = ConnectionDAO.getBoltSession();
Run Code Online (Sandbox Code Playgroud)

这种静态调用使一切变得困难。当然,您可以以某种方式对 ConnectionDAO 进行编码以将其初始化以进行单元测试,例如通过创建...

ConnectionDAO.initForTestOnly();
Run Code Online (Sandbox Code Playgroud)

...方法,但这意味着您的 ConnectionDAO 有两个作业,第一个是实际的 DAO,第二个是测试工具。这不是一个好主意,因为一个类应该只做一件事。

所以,我们通常会嘲笑一些东西。对于模拟的东西,您必须将依赖项提供给要模拟的类,而不是将它们硬编码到类中,例如......

class YourClass {

  private ConnectionDAO connectionDAO;

  public YourClass(ConnectioNDAO connectionDao) {
    this.connectionDAO = connectionDAO;
  }

  public String getProcessNames() throws IOException{
     ...
     Session session =  this.connectionDAO.getBoltSession();
     ...
  }

}
Run Code Online (Sandbox Code Playgroud)

这消除了对静态类的需要,现在您可以在测试类中模拟您的connectionDAO...

class YourClassTest {

   public void testGetProcessNames() throws IOException {
       ConnectionDAO connectionDAOMock = Mockito.mock(ConnectionDAO.class);
       YourClass yourClass = new YourClass(connectionDAOMock);

       //...init the mock here, see the Mockito documentation for that

       String result = yourClass.getProcessNames();


   }

}
Run Code Online (Sandbox Code Playgroud)

也许您需要对您的qpObj. 希望这个基本想法对开始有所帮助......