如何对无法实例化的对象进行单元测试?因为目前我有一个将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()); } }