Édipo Féderle
Édipo Féderle

Reputation: 4257

Testing Database Connection with DriverManager(java)

I currently am trying testing (unit test) a class that connect to the database, see the code:

public Connection getConnection() {
     System.out.println("Conectando ao banco");
     try {
         return DriverManager.getConnection("jdbc:postgres://localhost/banco", "root", "");
     } catch(SQLException e) {
         throw new RuntimeException(e);
     }
}

I liked know how i can mock(Jmock) it, but DriverManager isnt a interface so i cannot mock this class, so how i can make this test?

Upvotes: 0

Views: 3440

Answers (3)

David H. Clements
David H. Clements

Reputation: 3638

I know this is an older question, but came across it when dealing with a related problem.

Two strategies that might work for you:

1) Mock out getConnection() on your object so that you are returning the mock connection directly. There are a couple of different ways to do this depending on your exact use case, but in principle it is relatively straightforward.

2) Changing your mocking framework and taking advantage of PowerMock, which lets you mock out static methods on objects. It won't work with DriverManager specifically, but you can build a wrapper for this call in another class that it will work with.

Upvotes: 0

卢声远 Shengyuan Lu
卢声远 Shengyuan Lu

Reputation: 32014

So you could rethink your design. DAO can be an abstract layer between persistence and business logic. It can help you to unit test.

Upvotes: 0

duffymo
duffymo

Reputation: 308998

I see no point in mocking this. If your goal is to test whether you can connect to a database, what are you proving with a mock? Absolutely nothing, IMO.

Test your persistence classes by making a connection, performing operations, and rolling back your changes.

Once that's working, it's perfectly appropriate to mock the persistence classes when testing services, because you've already tested the persistence stuff.

But what you're proposing goes too far, IMO. Just run your test and get on with it.

Upvotes: 1

Related Questions