user3128303
user3128303

Reputation: 747

Unit tests for one main method

I have a method. What is the best practice to unit testing? You can make a mock Connection and ResultSet and pass as a method parameter as an object but I find it stupid, unprofessional solution.

public static void playA() {
    MyObject object = check("cat");
    // some stuff...
}

private static MyObject check(String s) throws SQLException {
    // some stuff checking string
    MyObject o = methodA(s);
    // some stuff doing on the object
    return o;
}

private static MyObject methodA(String s) throws SQLException {
    Connection c = MySettings.getConnection();
    PreparedStatement ps = c.prepareStatement("select * from Objects where type = ?");
    ps.setString(1, s);
    ResultSet resultSet = ps.executeQuery();
    while (resultSet.next()) {
        // mapping
        return object;
    }
    return null;
}

Upvotes: 0

Views: 53

Answers (1)

Nicolas Fontenele
Nicolas Fontenele

Reputation: 193

My take is that it should be according the level of abstraction you want to test. Mocking Connection and ResultSet can be fine if you want to check the the logic of your SQL for example.

If you want to be precise testing the database connection layer you can use tools for unit testing database like http://dbunit.sourceforge.net/

Also try to have your code as most Object Oriented as possible. that would help you in testing ( although I know it's probably just an example )

Upvotes: 1

Related Questions