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

前端 未结 8 1873
故里飘歌
故里飘歌 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:44

    If we limit the scope of discussion to Controller vs HttpClient testing comparison, I would say that it is better to use HttpClient. Because if you write tests for your controllers, you're already writing integration tests already and there is almost no point to write "weaker" integration tests while you can write stronger ones that is more realistic and also superset of the weaker ones.

    For example, you can see from your own example that both of your test are testing exactly the same functionality. The different is that the latter one cover more area of testing -- JSON response, or can be something else like HTTP header you want to test. If you write the latter test, you don't need the first test at all.

    I understand the pain of how to inject mocked dependencies. This requires more effort comparing to testing controller directly. However, .NET Core already provides a good set of tools to help you on that. You can setup the test host inside the test itself, configure it and get HttpClient from it. Then you can use that HttpClient for your testing purpose.

    The other concern is that it is quite a tedious task to craft HttpClient's request for each test. Anyway, Refit can help you a lot on this. Refit's declarative syntax is quite easy to understand (and maintain eventually). While I would also recommend Refit for all remote API calls, it is also suitable for ASP.NET Core integration testing.

    Combining all solutions available, I don't see why you should limit to controller test while you can go for more "real" integration test with only some little more effort.

提交回复
热议问题