如何对无法实例化的对象进行单元测试?因为目前我有一个将 ResultSet 转换为对象的方法,但我不确定这是否违反了任何编程原则。
public CItem convert(ResultSet rs) {
CItem ci = new CItem ();
try {
ci.setHinumber(rs.getString("id"));
ci.setHostname(rs.getString("sysname"));
ci.setOs(rs.getString("zos"));
ci.setTenant(rs.getString("customer_name"));
//ci.setInstallation(rs.getField("installation_name"));
} catch (SQLException e) {
e.printStackTrace();
}
return ci;
}
我是否需要寻找一种不同的方法来解决这个问题,仅仅是因为它无法进行单元测试?或者我能否以某种方式伪造一个 ResultSet 对象。
如有任何帮助,我们将不胜感激。
最佳答案
您可以简单地模拟您的 ResultSet
为每个字段提供一个值并检查结果是否包含您期望的内容。
例如 Mockito ,您的测试将是这样的:
@RunWith(MockitoJUnitRunner.class)
public class SomeClassTest {
@Mock
private ResultSet resultSet;
@Test
public void testConvert() throws SQLException {
// Define the behavior of the mock for each getString method's call
Mockito.when(resultSet.getString("id")).thenReturn("myId");
Mockito.when(resultSet.getString("sysname")).thenReturn("myHost");
Mockito.when(resultSet.getString("zos")).thenReturn("myOS");
Mockito.when(resultSet.getString("customer_name")).thenReturn("myCustomerName");
// Launch the method against your mock
SomeClass someClass = new SomeClass();
CItem item = someClass.convert(resultSet);
// Check the result
Assert.assertNotNull(item);
Assert.assertEquals("myId", item.getHinumber());
Assert.assertEquals("myHost", item.getHostname());
Assert.assertEquals("myOS", item.getOs());
Assert.assertEquals("myCustomerName", item.getTenant());
}
}
关于java - 单元测试以 ResultSet 作为参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41856442/