Laurens :
How does one go about unit testing an object that can't be instantiated? Because currently I have a method that converts a ResultSet to an object but I'm unsure if this violates any programming principles.
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;
}
Do I need to look for a different way to approach this solely because it can't be unit tested? Or can I somehow fake a ResultSet object.
Any help would be appreciated.
Nicolas Filotto :
You could simply mock your ResultSet
to provide a value for each field and check that the result contains what you expect.
For example with Mockito, your test would be something like this:
@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());
}
}
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=450681&siteId=1