ASP.NET Core TestServer为Razor视图生成HTTP 500

Bar*_*jen 4 asp.net-mvc razor asp.net-core-mvc asp.net-core

当我使用TestServer调用MVC端点来检查视图呈现时,它会导致HTTP 500内部服务器错误响应.

错误是:

在编译处理此请求所需的资源期间发生错误.请查看以下特定错误详细信息并相应地修改源代码.

/CustomSubfolder/Views/_ViewImports.cshtml

缺少一个或多个编译引用.可能的原因包括应用程序的project.json中'buildOptions'下缺少'preserveCompilationContext'属性.

类型或命名空间名称myNameSpace对象'不存在命名空间"Company.App"存在(是否缺少程序集引用?)

测试代码:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

namespace MvcProject.Tests
{
    [TestClass]
    public class ControllerTests
    {
        protected TestServer Server { get; }
        protected HttpClient Client { get; }

        public ControllerTests()
        {
            Server = new TestServer(new WebHostBuilder()
                .UseContentRoot("../../../../MvcProject")
                .UseStartup<Startup>());
            Client = Server.CreateClient();
        }

        [TestMethod]
        public async Task Action_Valid_Renders()
        {
            HttpResponseMessage response = await Client.GetAsync("http://localhost/");

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用面向.NET Framework 4.6.1的ASP.NET Core 1.1,我的MSTest .csproj文件如下所示:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net461</TargetFramework>
    <IsPackable>false</IsPackable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="1.1.3" />
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.3.0" />
    <PackageReference Include="MSTest.TestAdapter" Version="1.1.18" />
    <PackageReference Include="MSTest.TestFramework" Version="1.1.18" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\MvcProject\MvcProject.csproj" />
  </ItemGroup>

</Project>
Run Code Online (Sandbox Code Playgroud)

Bar*_*jen 8

https://github.com/aspnet/Razor/issues/1212中所述,问题是.deps.jsonRazor视图编译所需的文件不会自动复制到测试项目的输出中.

您可以将以下手动构建步骤添加到测试项目以解决该问题.

  <!--
    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>
Run Code Online (Sandbox Code Playgroud)