Is it best practice to test my Web API controllers directly or through an HTTP client?

前端 未结 8 1874
故里飘歌
故里飘歌 2021-02-05 10:08

I\'m adding some unit tests for my ASP.NET Core Web API, and I\'m wondering whether to unit test the controllers directly or through an HTTP client. Directly would look roughly

8条回答
  •  余生分开走
    2021-02-05 10:32

    TL;DR

    Is it best practice to test [...] directly or through an HTTP client?

    Not "or" but "and". If you serious about best practices of testing - you need both tests.


    First test is a unit test. But the second one is an integration test.

    There is a common consensus (test pyramid) that you need more unit tests comparing to the number of integration tests. But you need both.

    There are many reasons why you should prefer unit tests over integration tests, most of them boil down to the fact that unit test are small (in all senses) and integration tests - aren't. But the main 4 are:

    1. Locality

      When your unit test fails, usually, just from it's name you can figure out the place where the bug is. When integration test becomes red, you can't say right away where is the issue. Maybe it's in the controller.GetGroups or it's in the HttpClient, or there is some issue with the network.

      Also, when you introduce a bug in your code it's quite possible that only one of unit tests will become red, while with integration tests there are more chances that more than one of them will fail.

    2. Stability

      With a small project which you can test on you local box you probably won't notice it. But on a big project with distributed infrastructure you will see blinking tests all the time. And that will become a problem. At some point you can find yourself not trusting test results anymore.

    3. Speed

      With a small project with a small number of tests you won't notice it. But on a bit project it will become a problem. (Network delays, IO delays, initialization, cleanup, etc., etc.)

    4. Simplicity

      You've noticed it yourself.

      But that not always true. If you code is poorly structured, then it's easier to write integration tests. And that's one more reason why you should prefer unit tests. In some way they force you to write more modular code (and I'm not taking about Dependency Injection).

    But also keep in mind that best practices are almost always about big projects. If your project is small, and will stay small, there are a big chance that you'll be better off with strictly opposite decisions.

    Write more tests. (Again, that means - both). Become better at writing tests. Delete them latter.

    Practice makes perfect.

提交回复
热议问题