Unit test strategy – example on a common .Net application structure
A unit test is the smallest piece of testable software in the application, and the size of the unit under test is not strictly defined, so how to define a unit test strategy in a common .Net service structure?
Briefly introduce two types of unit tests before we apply them to the application.
Sociable unit testing focuses on testing the behavior of modules by observing changes in their state, we treat it as a black box.
Solitary unit testing looks at the interaction between the object and focuses on the isolation. (replaced by test doubles)
Let's see a typical web .Net application structure would look like this:
Recommended by LinkedIn
The user interface used to be exposed by the service and also act as a mapper to control the message in and out, normally it’s a thin layer and connects with the domain layer. The responsibility is for the sanity check of the request and response. Because its logic is more about the messages passing between modules rather than complex logic in the modules, we can use the test doubles strategy on this layer. If you feel like they are too many doubles, it is a good indication that you should extract some logic and test it isolated.
The gateway is used for communicating with external modules/services and the repositories is the layer working as a plumbing code, which is hard to test by the state change as well, so the more effective test way is by test doubles.
Domain’s logic is the most complex part of the application and it would be a collection of state transitions. There is only a little value to isolate all the units since the logic is highly state-based, which means we should use real domain objects under the test. In this layer, we can follow the Sociable unit testing strategy.
The intention of tests is to constrain the code behavior, however, the side effect happened sometimes by mocking approach which constrains the implementation. It is important to question the value of a unit test provides versus the cost of maintenance or the amount that constrains the implementation, then we can always focus on a high-value unit test.
31/05/2022
Note: The banner is from my mother's painting: The Australia flower