gpt4 book ai didi

unit-testing - 如何使用 microsoft.aspnetcore.testhost 测试 asp.net core 1.1 mvc 操作返回 Razor View

转载 作者:行者123 更新时间:2023-12-01 12:22:33 25 4
gpt4 key购买 nike

使用 Microsoft.aspnetcore.testhost 我无法使 http get 到返回 Razor View 的 Controller 操作。我需要测试响应是否具有特定的安全 header ,以及我想对操作响应执行的其他测试。Razor 为它命中的每个命名空间抛出编译异常,而不仅仅是下面的系统示例:

oclq12bb.ugz(5,11): error CS0246: The type or namespace name 'System' could
not be found (are you missing a using directive or an assembly reference?)
oclq12bb.ugz(6,11): error CS0246: The type or namespace name 'System' could
not be found (are you missing a using directive or an assembly reference?)

复制:

  • 使用 visual studio 2017 创建一个新的 asp.net core 1.1 网络项目并添加一个 .net 核心单元测试项目。
  • 从启动中删除应用程序设置。
  • 将 View /home/index.cshtml 复制到输出目录设置为“始终复制”。
  • 创建并运行单元测试。抛出异常。

代码:

[TestClass]
public class UnitTest1
{
private readonly HttpClient _client;

public UnitTest1()
{
var server = new TestServer(
new WebHostBuilder().UseStartup<Startup>());
_client = server.CreateClient();
}

[TestMethod]
public async Task Test1()
{
var response = await _client.GetAsync("/");
}
}

我尝试将 Web 项目发布到一个文件夹,并始终使用 .UseContentRoot() 代替复制。相同的结果。

最佳答案

longday 的评论实际上对我有用。为了让这个问题得到解答并对其他人更有用,让我放上实际有效的代码。这是我项目中的代码,但它非常通用。

using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.TestHost;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions;
using Shevastream.Models;
using Shevastream.Services.Factories;
using Xunit;

namespace Shevastream.Tests.IntegrationTests
{
public class PagesTests
{
/// <summary>
/// Server object which mimics a real running server
/// </summary>
private readonly TestServer _server;
/// <summary>
/// Client object which mimics a real client
/// </summary>
private readonly HttpClient _client;

private readonly IDataContext _dataContext;

/// <summary>
/// Setup mock server and client
/// </summary>
public PagesTests()
{
var path = PlatformServices.Default.Application.ApplicationBasePath;
var contentPath = Path.GetFullPath(Path.Combine(path, $@"../../../../src"));

_server = new TestServer(
new WebHostBuilder()
.UseContentRoot(contentPath)
.UseStartup<Startup>()
.ConfigureServices(services =>
{
services.AddSingleton<IHttpClientFactory, HttpClientFactory>();
services.Configure((RazorViewEngineOptions options) =>
{
var previous = options.CompilationCallback;
options.CompilationCallback = (context) =>
{
previous?.Invoke(context);

var assembly = typeof(Startup).GetTypeInfo().Assembly;
var assemblies = assembly.GetReferencedAssemblies().Select(x => MetadataReference.CreateFromFile(Assembly.Load(x).Location))
.ToList();
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("mscorlib")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Private.Corelib")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.AspNetCore.Razor")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("mscorlib")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Private.Corelib")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Linq")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Threading.Tasks")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Runtime")).Location)); assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Dynamic.Runtime")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.AspNetCore.Razor.Runtime")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.AspNetCore.Mvc")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.AspNetCore.Razor")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.AspNetCore.Mvc.Razor")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.AspNetCore.Html.Abstractions")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Text.Encodings.Web")).Location));

context.Compilation = context.Compilation.AddReferences(assemblies);
};
});
})
);

_client = _server.CreateClient();

var serviceProvider = Extensions.RegisterServices().BuildServiceProvider();
_dataContext = serviceProvider.GetRequiredService<IDataContext>();
}

[Theory]
[InlineData("/home")]
[InlineData("/home/profile")]
[InlineData("/store/product")]
[InlineData("/home/contact")]
[InlineData("/store/cart")]
[InlineData("/home/faq")]
[InlineData("/account/login")]
public async Task TestSimplePages(string url)
{
// Act
var ok = await _client.GetAsync(url);

// Assert
Assert.Equal(HttpStatusCode.OK, ok.StatusCode);
}
}
}

关于unit-testing - 如何使用 microsoft.aspnetcore.testhost 测试 asp.net core 1.1 mvc 操作返回 Razor View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42737385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com