[英]Unit test DB calls
我有一个带有静态函数的类,该函数执行数据库操作,例如保存,检索和删除。
我的数据库课程:
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
测试的方式saveObject
正确的吗? 我是单元测试的新手,所以我不知道最佳实践以及如何涵盖所有情况。
@Mock
Statement statement;
doReturn(statement).when(connection).prepareStatement(anyString());
doNothing().when(statement).setObject(any(), any());
doNothing().when(statement).executeUpdate();
这只是使用Mockito。 您也可以使用PowerMockito。 它仍然应该起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.