我想为我的网络应用程序编写集成测试。我用了Microsoft.AspNetCore.TestHost.TestServer
通过 url 与 Controller 通信。但是无法呈现 View 。作为回应,我收到错误消息:
One or more compilation references are missing. Ensure that your project is referencing 'Microsoft.NET.Sdk.Web' and the 'PreserveCompilationContext' property is not set to false.
在我的 .csproj 中,我尝试在 Microsoft.NET.Sdk.Web
上更改 project-sdk ,我尝试添加 <PreserveCompilationContext>true</PreserveCompilationContext>
.我还尝试按照 Microsoft 文档(here 中的 here)中的描述重写代码。
但我仍然有相同的错误消息。
重现步骤:
- 创建测试项目“
WebApplication1.IntegrationTests
”。 - 添加对 WebApplication 项目的引用。
- 添加 nuget 包“
Microsoft.AspNetCore.TestHost
” - 通过
TestServer
向“/Home/Index”发送获取请求. - 读取带有错误消息的响应。
using WebApplication1;
using Microsoft.AspNetCore.TestHost;
using System.Net.Http;
using System.Threading.Tasks;
namespace WebApplication1.IntegrationTests
{
public class Program
{
public static void Main(string[] args)
{
// Path to contentRoot folder.
var contentRootPath = @"..\..\..\..\WebApplication1";
var builder = new WebHostBuilder()
.UseStartup<Startup>()
.UseEnvironment(EnvironmentName.Development)
.UseContentRoot(contentRootPath);
var server = new TestServer(builder);
var client = server.CreateClient();
var response = client.GetAsync("/Home/Index").Result;
var responseString = response.Content.ReadAsStringAsync().Result;
}
}
}
最佳答案
最近为了测试 ASP.NET Core 2.0 应用程序,我不得不用 <PreserveCompilationContext>true</PreserveCompilationContext>
更新集成测试项目的 csproj 文件。属性和一个额外的目标来复制 .deps.json
文件。
<!--
Work around https://github.com/NuGet/Home/issues/4412. MVC uses DependencyContext.Load() which looks next to a .dll
for a .deps.json. Information isn't available elsewhere. Need the .deps.json file for all web site applications.
-->
<Target Name="CopyDepsFiles" AfterTargets="Build" Condition="'$(TargetFramework)'!=''">
<ItemGroup>
<DepsFilePaths Include="$([System.IO.Path]::ChangeExtension('%(_ResolvedProjectReferencePaths.FullPath)', '.deps.json'))" />
</ItemGroup>
<Copy SourceFiles="%(DepsFilePaths.FullPath)" DestinationFolder="$(OutputPath)" Condition="Exists('%(DepsFilePaths.FullPath)')" />
</Target>
您可以查看完整集成测试项目的源代码in github .可能还有其他差异,比如我使用了完整路径 .UseContentRoot(path)
方法。
关于c# - AspNetCore v2.0 — 在另一个项目中呈现 razor-views 以进行集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47632878/