简体   繁体   English

一种主要方法的单元测试

[英]Unit tests for one main method

I have a method. 我有办法 What is the best practice to unit testing? 什么是单元测试的最佳实践? You can make a mock Connection and ResultSet and pass as a method parameter as an object but I find it stupid, unprofessional solution. 您可以制作一个模拟Connection和ResultSet并作为方法参数作为对象传递,但是我发现它是愚蠢的,非专业的解决方案。

public static void playA() {
    MyObject object = check("cat");
    // some stuff...
}

private static MyObject check(String s) throws SQLException {
    // some stuff checking string
    MyObject o = methodA(s);
    // some stuff doing on the object
    return o;
}

private static MyObject methodA(String s) throws SQLException {
    Connection c = MySettings.getConnection();
    PreparedStatement ps = c.prepareStatement("select * from Objects where type = ?");
    ps.setString(1, s);
    ResultSet resultSet = ps.executeQuery();
    while (resultSet.next()) {
        // mapping
        return object;
    }
    return null;
}

My take is that it should be according the level of abstraction you want to test. 我的观点是,它应该根据您要测试的抽象级别。 Mocking Connection and ResultSet can be fine if you want to check the the logic of your SQL for example. 例如,如果您想检查SQL的逻辑,则可以模拟连接和ResultSet。

If you want to be precise testing the database connection layer you can use tools for unit testing database like http://dbunit.sourceforge.net/ 如果要精确测试数据库连接层,可以使用用于单元测试数据库的工具,例如http://dbunit.sourceforge.net/

Also try to have your code as most Object Oriented as possible. 还尝试使您的代码尽可能地面向对象。 that would help you in testing ( although I know it's probably just an example ) 这将帮助您进行测试(尽管我知道这可能只是一个例子)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM