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

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

    I'd say that they are not mutually exclusive. The first option is a classical unit test while the second is an integration test as involves more than a single unit of code.

    If I had time to write either unit tests or integration tests, I'd pick unit tests as provides a more focused approach and gives, at least in my opinion, the best result from cost benefit.

    In some particular projects where I had enough resources to write different suites of tests, I wrote both tests covering approaches. Where the second one would run without mocking anything (or maybe just the persistent storage) so I could test how all the components integrate together.

    In relation to good practices, if you want to do real unit test, then you have no option but picking option one as no external dependencies are allowed (HttpClient is an external dependency).

    Then, if the time and resources allow it, you could do integration testing for the most critical and/or complex paths.

提交回复
热议问题