0

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?

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Sure, you're right, but how could I test inserts and update for example without touching the database at all. Its not?
If you don't touch the database you're not testing anything. You can't do it. So write the tests.
0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.