0

I want to write an API test, kind of end-to-end test, for my application.

Assume that I want to get all Foos in the system. When I hit an endpoint /foo/all, I fetch data using HTTPClient and get some dependent objects of Foo from another microservice Bar.

My unit tests are ok. I can also boot my api for tests , however I don't want to call Bar service as I don't want its dependency on my tests, instead, I want to make something like a stub.

So how can I mock those services? I cannot mock HttpClient and override ConfigureServices method in my test application bootstrap process, because HttpClient does not implement any interface.

Thanks.

skynyrd
  • 942
  • 4
  • 14
  • 34
  • You are not supposed to replace `HttpClient` but your service class which abstracts the `HttpClient`. i.e. `IUserService` and `UserService` which uses the `HttpClient` to perform the calls. In this case instead of injecting `UserService` you mock `IUserService` and register this as dependency. It's tricky since you'd have to do the replacements after `IServiceCollection` has been populated, but before `IServiceProvider` was created (usually between `ConfigureServices` and `Configure` method) – Tseng May 17 '17 at 11:53
  • For ASP.NET Core, you might want to take a look at this document which has a section on unit testing controllers with an example using POST https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/testing – Svek May 17 '17 at 12:01
  • @Tseng Yes I can mock my service that uses HttpClient, however this time I cannot test inside of that method. For example in `GetAllUsers()` in `UserService` can make an http call to another microservice, but can also add some logic before passing it back. So do you mean the UserService is not like a domain model, but something like anti corruption layer? – skynyrd May 17 '17 at 12:04
  • @Svek thanks for your response but I already implemented controller unit tests. I just want something like end to end tests, starting from controller, visiting the test db and returning back. – skynyrd May 17 '17 at 12:06
  • 1
    Look at this answer: http://stackoverflow.com/a/36427274/5112433 – Ilya Chumakov May 17 '17 at 12:10
  • Yes definetely looking for something like that, thanks @IlyaChumakov – skynyrd May 17 '17 at 12:21

0 Answers0