Unit testing of a method that takes a ResultSet parameter as a parameter

How to do unit testing of an object that cannot be created? Since I currently have a method that converts a ResultSet into an object, but I'm not sure if this violates the principles of programming.

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;
}

Is there a need to look for another way to approach this only because it cannot be checked by the module? Or I can somehow fake a ResultSet object.

Any help would be appreciated.

+4
source share
2 answers

You can simply make fun of yours ResultSetto provide a value for each field and verify that the result contains what you expect.

, 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 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());
    }
}
+6

, ResultSet .

, ​​ Mockito Power Mock, ResultSet. , (, / JDK).

, ResultSet Order. , , " ", , . .

interface OrderRepository {
    OrderData get();
}

, JDBCOrderRepository, ResultSet. ('convert') OrderRepository ResultSet. , OrderRepository ResultSet, .

, JDBCOrderRepository? , , .

+1

Source: https://habr.com/ru/post/1667788/


All Articles