[英]How to test a controller in .NET Core
I have an ASP.NET Core application ( NetCoreApp1.1
) Web API project and I would like to test a controller of that project. 我有一个ASP.NET核心应用程序( NetCoreApp1.1
)Web API项目,我想测试该项目的控制器。 I added a .NET Core class library (targeting NetStandard1.6
). 我添加了一个.NET Core类库(针对NetStandard1.6
)。
Now the problem I have is that according to Why doesn't Microsoft.NETCore.App support netstandard1.6? 现在我的问题是根据为什么Microsoft.NETCore.App不支持netstandard1.6? I can't reference the Web API project from that class library. 我无法从该类库中引用Web API项目。
My question is then, does this mean that unless the controllers are placed somewhere else I won't be able to test them anymore? 我的问题是,这是否意味着除非将控制器放在其他地方,否则我将无法再测试它们了? Maybe there is a way to do so but I haven't been able to achieve it in VS 2017 RC. 也许有办法这样做,但我无法在VS 2017 RC中实现它。
Test projects should be console applications, not class libraries. 测试项目应该是控制台应用程序,而不是类库。 A console application references Microsoft.NETCore.App
and shouldn't have any problems referencing your Web API project. 控制台应用程序引用Microsoft.NETCore.App
并且在引用Web API项目时不应该有任何问题。
A simple example of the project.json
for a working test project is: project.json
用于工作测试项目的一个简单示例是:
{
"dependencies": {
"dotnet-test-xunit": "2.2.0-preview2-build1029",
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.1"
},
"xunit": "2.1.0",
"MyApiProject": {
"target": "project"
}
},
"frameworks": {
"netcoreapp1.0": {
"imports": "dotnet"
}
},
"testRunner": "xunit",
}
If you're using .csproj
in VS 2017, it'll look different, but the principle should be the same. 如果你在VS 2017中使用.csproj
,它看起来会有所不同,但原则应该是一样的。 The test project can reference the API project locally, and uses a test runner like Xunit to run tests. 测试项目可以在本地引用API项目,并使用像Xunit这样的测试运行器来运行测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.