2

Let's assume, that frameworks I use, provide some kind of dependency injection automatically available in testing environment.

Let's also assume, that I have a lot of micro services in my application. Testing each of them separately in ideal unit tests scenarios doesn't bring too much value to me. It is usually because these are really trivial and there are no too many mistakes the developer can commit. Most of errors go from some bad interactions between micro services, so I prefer to test facades that integrate/use them.

I came up onto two different approaches in tests:

  1. Traditional unit tests, where I instantiate tested services directly and I have to explicitly pass all dependencies either mocks or real services.

    Some cons of this approach include:

    • Frequent changes of what a service depends on causes frequent changes of its tests.
    • I cannot detect DI related issues like missing factories/containers/providers or circular dependencies which use to be very frequent issues in my project. Removed after @VincentSavard's comment -it can be handled by separated tests.
    • Please see edit.
  2. To use DI mechanism. First, I can define which services I want to mock, then the framework instantiates all other dependencies as "reals"

    Cons of this approach:

    • During the application evolution, the dependency tree eventually "smuggles" some services which can cause some invisible troubles in existing tests. It is extremely difficult to trace then the "path" of dependencies that leads to the troublesome service.

My question is: which of these approaches is better in terms of best test design practices? Or maybe there is some other approach?

Edit

After comment from @VincentSavard I realized that I forgot about one downside of 1st approach. The framework provides some kind of isolation for microservices. Using the 1st approach requires microservices to be exposed to some kind of global scope.

  • 1
    They're not mutually exclusive. Test the behaviour of your code without the use of your DI framework, then test that you correctly set up your DI framework without testing the behaviour of your code. There are two completely different things you want to test here. – Vincent Savard Mar 5 at 17:25

Your Answer

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

Browse other questions tagged or ask your own question.