Home > Enterprise >  How to write unit testing friendly code in ASP.NET Core 6.0?
How to write unit testing friendly code in ASP.NET Core 6.0?

Time:10-23

I tried to find the unit testing-friendly best code practice in .NET development.

I'm assuming that it will be painful if I got to implement unit testing for an already developed project which is not planned to do unit testing when it was developed.

  • What are things we need to keep in mind when we develop Web API or web applications?
  • What is the best unit testing-friendly architecture?
  • What are the principles which we need to follow. eg: Interface segregation in SOLID principles.

CodePudding user response:

I'm assuming that it will be painful if I got to implement unit testing for an already developed project which is not planned to do unit testing when it was developed.

Indeed an already existing projects with no (or few) tests is not the best motivator for writing new tests.

In such case, I would recommend to consider those all never-written tests as tech debt, and start writing tests for new modules only. With time, you will probably find yourself covering old modules as part of fixing bugs (and bugs are likely to be found in old module because, well, they had never been covered with tests).

Secondly, the process of writing tests in a project with lots of untested code can itself lead to make necessary design changes. Not only that unit tests help us finding bugs in dev-time and have regression cover, but also they promote better design in our systems.

What are things we need to keep in mind when we develop Web API or web applications?

Big question. There are many aspects for a good app and lots of docs on web to learn from. I can give you a specific view in the context of unit tests: use interfaces, and follow the dependency-injection and dependency-inversion principles. This way, it will be easy to write tests, which in turn improve the quality of your app.

What is the best unit testing-friendly architecture?

I am not sure that 'architecture' is the accurate term. There are however several approaches for writing tests, such as TDD and BDD, but you have to keep in mind that writing tests with, for example, the TDD approach might require a learning curve for developers.

Use one of the many frameworks available for writing unit tests, and start writing tests for methods. Check outputs against inputs and mock-objects, and learn how to pick best sample data as inputs for your tests.

What are the principles which we need to follow. eg: Interface segregation in SOLID principles.

Again, big question. In short: SOLID.

  • Related