How do I mock database tables using java and mockito? (springboot, mockito)

I need to be able to mock a table in mockito for testing queries.

i.e. I have a Predicate

public Preciate makePredicate(){
 return criteriaBuilder.like(tableRoot.get(col), "test"); 
}

and I want to be able to test something like this

criteriaQuery.where(makePredicate());
ResultSet res = criteriaQuery.getResultSet();

and verify values in res

I need to be able to mock a table of a database and be able to insert mocked values into the table but I am not sure how to do that.

Upvotes: 0

Views: 1702

Answers (1)

ddewaele
ddewaele

Reputation: 22603

Mocking a table is the wrong level of abstraction for your tests, unless you are writing some kind of very low level DB library.

In your case you would either

  • just rely in an in memory database for integration tests, so that you can properly test the interaction with the DB, especially if your are using JDBC. I think this option would be appropriate for you as you seem to be operating at a level fairly close to the DB (resultsets, criteriabuilders,...). In an integration test with an in memory DB it is very easy to insert data in a table as well. Your tests will then cover a lot.
  • opt to do only pure unit tests without a DB, and mock at the level of the service that is doing the interaction with the DB. However, be aware that in this case you will not be able to test your JDBC related code

I would personally cover in an integration test with an in memory database.

Generally speaking you don't want to mock the JDBC library or the database as that would be impossible and would require an immense knowledge of the underlying calls between JDBC and the DB.

Upvotes: 3

Related Questions