ASP.NET Core TestServer Displays HTTP 500 for Razor Views

When I use TestServerMVC to invoke the endpoint to verify the rendering of the view, it triggers a response to an internal HTTP 500 server error.

Error:

An error occurred while compiling the resource required to process this request. Review the following specific error data and modify the source code accordingly.

/CustomSubfolder/Views/_ViewImports.cshtml

One or more compilation links missing. Possible reasons include the missing preserveCompilationContext property in 'buildOptions' in the project.json application.

The type or namespace name 'MyNamespace' does not exist in the namespace 'Company.App' (do you miss the assembly reference?)

Test code:

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);
        }
    }
}

ASP.NET Core 1.1 .NET Framework 4.6.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>
+4
1

https://github.com/aspnet/Razor/issues/1212, , .deps.json , Razor, .

, .

  <!--
    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>
+7

Source: https://habr.com/ru/post/1686524/


All Articles