编程语言
首页 > 编程语言> > C#-AspNetCore v2.0-在另一个项目中渲染剃刀视图以进行集成测试

C#-AspNetCore v2.0-在另一个项目中渲染剃刀视图以进行集成测试

作者:互联网

我想为我的Web应用程序编写集成测试.我使用Microsoft.AspNetCore.TestHost.TestServer通过url与控制器进行通信.但是视图无法呈现.作为回应,我收到错误消息:

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&gt ;.我也尝试按照Microsoft-docs(here中的here)中所述重写代码.
但是我仍然有同样的错误信息.

重现步骤:

>创建测试项目“ WebApplication1.IntegrationTests”.
>在WebApplication-project上添加参考.
>添加nuget程序包“ Microsoft.AspNetCore.TestHost”
>通过TestServer将get-request发送到“ / 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;
        }
    }
}

在浏览器中呈现的responseString:
enter image description here

解决方法:

为了最近测试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)方法一起使用.

标签:razorengine,asp-net-core-mvc,asp-net-core-2-0,asp-net,c
来源: https://codeday.me/bug/20191110/2014523.html