我有一个带有静态函数的类,执行数据库操作,例如保存,检索和删除。
我的数据库类:
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
测试的方式是否正确?我是单元测试的新手,所以我不知道最佳实践以及如何涵盖所有情况。
@Mock
Statement statement;
doReturn(statement).when(connection).prepareStatement(anyString());
doNothing().when(statement).setObject(any(), any());
doNothing().when(statement).executeUpdate();
这是只使用Mockito。您也可以使用PowerMockito。它应该同样有效。