How to debug/unit test webAPi in one solution

2020-06-08 13:04发布

Is there a way to unit test or debug a web api in one vs solution? I am consuming the WebAPI using HttpClient and have two instances of VS up to do this.

in 1 VS instance I have the unit test, in the second vs instance I have the webapi running in localhost.

Is there a better way to do this?

Is the preferred way to unit test is to have a reference to the WebAPI project?

I want to consume it using httpClient and not have to reference it in the UnitTest Project.

so in my UnitTest method it would have a baseAddress of "http://localhost:1234"

this would be where the WebAPI if launched from the same solution would be hosted.

The current way I am debugging requires me to launch a second Visual Studio instance with the same solution loaded and have one running the WebAPI project, while the other Visual Studio runs the Unit Test project.

7条回答
趁早两清
2楼-- · 2020-06-08 13:59

As Daniel Mann stated, this isn't unit testing. This is integration testing. You are running up the entire project and testing everything.

If you want to unit test you webapi controllers, just add a unit test project to webapi project and create unit tests. You want to focus on testing only a single class at a time. Mock/Fake any dependencies of that class.

Here's a nice example from Microsoft http://www.asp.net/web-api/overview/testing-and-debugging/unit-testing-with-aspnet-web-api

but if what you are looking for is running the test you have in a single solution. Just put both projects in the same solution. Right click on the solution in the solution explorer. Select "Set StartUp projects." select "multiple startup projects" and select the projects you want to startup at the same time.

查看更多
登录 后发表回答