在开始 .Net 单元测试之前运行一个项目。

huangapple go评论56阅读模式
英文:

Run a project before starting .Net Unit Tet

问题

我有3个使用.NET 7.0制作的项目。

第一个是一个REST API。
第二个是一个REST客户端。
第三个是一个单元测试项目。

当我启动单元测试时,我希望以一个指定的端口号启动服务器。
然后,我的单元测试使用REST客户端与REST API进行通信。

我如何在单元测试开始之前启动Web服务?

英文:

I have 3 projects made with .Net 7.0

The first is a REST API.
The second is a REST Client.
And the third is a Unit Test project.

When I start the unit test I would like to start the server with a defined port number.
Then my unit test use the REST Client to talk to the REST API.

How can I start a web service before my unit test start ?

答案1

得分: 1

如在评论中提到的,如果您想测试控制器操作中包含的逻辑,您应该使用集成测试,而不是单元测试。使用集成测试,您可以设置一个类似于 HttpClientFactory 的 WebApplicationFactory。通过这种方式,您可以创建一个连接到 API 的客户端,以模拟请求在生产环境中的工作方式,从而测试所有组件如何协同工作。

集成测试的设置更加复杂,因此如果您刚刚开始这个项目,我建议将控制器操作中的逻辑移动到一个单独的辅助类中,然后对其进行单元测试。

英文:

As mentioned in the comments, if you want to test the logic contained in your controller actions you'll want to use integration tests, not unit tests. With integration tests you can set up a WebApplicationFactory that works similarly to a HttpClientFactory. With this, you create a client connected to the API that lets you simulate requests as they would be in a production environment in order to test how all components work together.

Integration testing is more complicated to set up, so if you're just getting started with this project, I'd recommend moving the logic in your controller actions into a separate helper class, and run the unit tests on those instead.

huangapple
  • 本文由 发表于 2023年3月9日 18:35:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75683409.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定