0

Let's say we have a simple application that uses a popular approach as Controller -> Service -> Repository pattern under a framework.

We would like to write integration tests and start from Controller. Any integration tests against a controller component will eventually run service component instances and my question is, does not it mean we also tested the service layer's functionality in this case? Even more, we have also tested the repository since in integration tests we generally don't mock internal integrations.

aController
  Service service;
  aControllerMethod(): 
    service.doBusiness(); //this will be called in controller integration test

--

aControllerIntegrationTest
  aControllerTestMethod():  
    testController();

In my opinion, the above case is true that it will test also the service layer. But except acceptance tests, we should write isolated tests and every layer should be also tested independently.

1
  • 1
    If you want/can cover all possible cases in controller tests, then you can skip on testing internal layers separately.
    – Fabio
    Dec 11 '21 at 23:15
3

That is correct. But this doesn't mean that we need to test everything via controllers. Each layer has its own logic and we may have many conditions to test, if we test everything through the highest level, then those tests will be hard to debug and slow to run. Instead:

  1. We write as many tests as possible for the layer where the logic resides.
  2. And then we have to check that the upper layer invoked the lower layer correctly, so we'll have fewer tests there. Thus there will be a necessary overlap with the lower-layer tests.

Ideally, our business logic will reside in our domain model and most of the complexity will be there. This will allow us to cover most of the logic with unit tests. And then write a smaller number of tests for the higher layers. This is called a Test Pyramid.

For more information:

1
  • Thanks @Stanislav for the answer. I totally agree that we need to test every layer separately in the context of integration testing. Because this will definitely be suggested by SoC. And even more if we are doing OOP, it is suggested to use the API approach for our software components. IMHO, since APIs should be tested by the implementation owner I believe this is also a supporting idea for why we need to test layers separately.
    – memoricab
    Dec 12 '21 at 13:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.