Search code examples
javaunit-testingmockitopowermockpowermockito

Unit test DB calls


I have a class with static functions performing DB operations such as save, retrieve and delete.

My DB class:

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

    }

}

I wrote a unit test to test it like this:

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

When i try to run this unit test i get a null pointer error at the statement = connection.prepareStatement line which is to be expected i think since I'm not mocking the connection properly. How do I mock the connection properly? Also is the way I have written the saveObject test correct? I am new to unit-testing so I don't know the best-practices and how to cover all cases.


Solution

  • @Mock
    Statement statement;
    
    doReturn(statement).when(connection).prepareStatement(anyString());
    doNothing().when(statement).setObject(any(), any());
    doNothing().when(statement).executeUpdate();
    

    This is using just Mockito. You can as well use PowerMockito. It should work none the less.