0

a discussion that rose among us devs: how to do unit test of Business logic layer that depends on data access layer. the two options are

  1. create test data in a test database (for example, H2). let the Business logic layer call the real data access layer that is injected with test database connection.

  2. mock the data access layer.

I can see pros and cons for the two options:
option one imitates production more closely. however, it compromises the isolation of the unit test. the test might fail because of a bug in the data access layer.
The 2nd option is vulnerable to the scenario where the logic inside the data access layer changes (with no changes to the api). in that case, the returned mocked value maybe obsolete.

would love to hear opinions on the matter (perhaps more options?)

2 Answers2

3

Both options are valid and have advantages and disadvantages:

  • Option 2 is correct from "idiomatic" point of view because "unit" tests shouldn't depend on code outside of the unit (class, layer, etc).
  • Option 1 leads to creating "integration" tests and as you stated, that's closer to the production usage and verifies that the different layers work together correctly.

In the end of the day use whatever works for you, even both types of tests simultaneously.

3

I think that it depends on which one is important for you.

I wrote unit tests in 2 different projects in a company where I had been working for a while.

Pros of mocking

  • The Unit Tests run fast according to saving really data to DB.
  • You do not have to maintain an extra database. Because if you are going to save data in reality, you have to create a test DB.
  • Sometimes DB connection problems might break your test even if your tests are not broken.

Pros of using real DB connection

  • You do not have to create an extra mock model each time.
  • Less complexity according to mocking.

Either way has its own pros and can be choosable rather than the other one.