单元测试DB调用

时间:2017-05-11 12:23:55

标签: java unit-testing mockito powermock powermockito

我有一个具有执行数据库操作(如保存,检索和删除)的静态函数的类。

我的数据库课程:

public final class DbUtils {

    static {
        DB_USER = //get from secure server
        DB_PASSWORD = //get from secure server
    }


    private static Connection establishConnection() {
    }

    private static void closeConnection(Connection connection) {

    }

    public static boolean saveObject(final Object graph, final Object map) {

        Connection connection = establishConnection();
        try {
            byte[] bgraph = ConvertToByte(graph);
            byte[] bmap = ConvertToByte(map);
            statement = connection.prepareStatement("INSERT IGNORE INTO " + TABLE_NAME + " VALUES (?,?)");
            statement.setObject(1, graph);
            statement.setObject(2, map);
            statement.executeUpdate();
            //Close statement within try catch
        } catch(Exception e) { // also other exception
            //catch to catch all type of exception
        }
        closeConnection(connection);
        return true;
    }

    public static Map<String, Object> retrieveObject(final String key) {
        Connection connection = establishConnection();
        //read byte and convert to object
        closeConnection(connection);
        return map;
    }

    public static boolean deleteObject(final String key) {
        Connection connection = establishConnection();
        //delete all object except object with key
        closeConnection(connection);
        return (affectedRow >= 1);

    }

}

我写了一个单元测试来测试它:

@RunWith(PowerMockRunner.class)
@PrepareForTest(DbUtils.class)
@SuppressStaticInitializationFor("DbUtils")
public class DbUtilsTest {

    @Mock
    Connection connection;

    @Mock
    ModuleDependencyGraph dependencyGraph;

    @Mock
    private Map<String , String> moduleSDF;

    @Test
    public void testSaveObject() throws Exception {
        PowerMockito.spy(DbUtils.class);
        PowerMockito.doReturn(connection).when(DbUtils.class, "establishConnection");
        Assert.assertTrue(DbUtils.saveObject(dependencyGraph, moduleSDF));
    }
}

当我尝试运行此单元测试时,我在statement = connection.prepareStatement行得到一个空指针错误,这是我预计的,因为我没有正确地模拟连接。如何正确模拟连接?我写saveObject测试的方式也正确吗?我是单元测试的新手,所以我不知道最佳实践以及如何涵盖所有案例。

1 个答案:

答案 0 :(得分:0)

@Mock
Statement statement;

doReturn(statement).when(connection).prepareStatement(anyString());
doNothing().when(statement).setObject(any(), any());
doNothing().when(statement).executeUpdate();

这只是使用Mockito。您也可以使用PowerMockito。它应该可以工作。