【问题标题】:Setup View engine in ASP.NET MVC6 to work with AspNet.TestHost.TestServer in Unit Tests在 ASP.NET MVC6 中设置视图引擎以在单元测试中使用 AspNet.TestHost.TestServer
【发布时间】:2015-10-02 22:29:50
【问题描述】:

如何在ASP.NET MVC 6 中设置视图引擎以使用TestServer 创建的测试主机。我尝试从MVC 6 repo 实现trick

[Fact]
public async Task CallMvc()
{
    var client = GetTestHttpClient();

    //call to HomeController.Index to get Home/Index.cshtml content
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "/");

    var response = await client.SendAsync(request);
    var content = await response.Content.ReadAsStringAsync();
    PAssert.IsTrue(() => content != null);
}

private HttpClient GetTestHttpClient(Action<IServiceCollection> configureServices = null)
{
    var applicationServices = CallContextServiceLocator.Locator.ServiceProvider;
    var applicationEnvironment = applicationServices.GetRequiredService<IApplicationEnvironment>();
    var libraryManager = applicationServices.GetRequiredService<ILibraryManager>();
    var startupAssembly = typeof(Startup).Assembly;

    var applicationName = startupAssembly.GetName().Name;
    var library = libraryManager.GetLibraryInformation(applicationName);
    var applicationRoot = Path.GetDirectoryName(library.Path);

    var hostingEnvironment = new HostingEnvironment()
    {
        WebRootPath = applicationRoot
    };

    var loggerFactory = new LoggerFactory();

    var startup = new Startup();

    Action<IServiceCollection> configureServicesAction = services =>
    {
        services.AddInstance(applicationEnvironment);
        services.AddInstance<IHostingEnvironment>(hostingEnvironment);

        // Inject a custom assembly provider. Overrides AddMvc() because that uses TryAdd().
        var assemblyProvider = new FixedSetAssemblyProvider();
        assemblyProvider.CandidateAssemblies.Add(startupAssembly);
        services.AddInstance<IAssemblyProvider>(assemblyProvider);

        startup.ConfigureServices(services);
    };

    Action<IApplicationBuilder> configureApp = _ => startup.Configure(_, hostingEnvironment, loggerFactory);
    var server = TestServer.Create(configureApp, configureServicesAction);
    var httpClient = server.CreateClient();

    return httpClient;
}

Startup 类只是 MVC 最简单的设置:

public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add MVC services to the services container.
        services.AddMvc();
    }

    // Configure is called after ConfigureServices is called.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {       
        // Add MVC to the request pipeline.
        app.UseMvc(routes =>
        {
            routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

我收到Response status code does not indicate success: 500 (Internal Server Error),但在内部它无法找到 Index.cshtml 视图。所有路径 以下是单元测试库路径或 dnx 路径:

var applicationBasePath = _appEnvironment.ApplicationBasePath;
var webRootPath = _env.WebRootPath;
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory; 

使用 TestServer 设置视图引擎和环境以从 UnitTests 工作的方法是什么?

【问题讨论】:

    标签: c# asp.net-mvc unit-testing asp.net-core-mvc viewengine


    【解决方案1】:

    您定义不同环境的想法正朝着正确的方向发展。

    我已经看到了一个非常优雅的解决方案,方法是使用扩展方法:

    https://github.com/bartmax/TestServerMvcHelper

    它甚至在 NuGet 上,但我无法从那里开始工作。可能您可以将两个类 MvcTestApplicationEnvironment.csWebHostBuilderExtensions.cs 合并到您的解决方案中。

    然后您可以使用以下方法设置 TestServer:

    var builder = TestServer.CreateBuilder();
    builder.UseStartup<Startup>()
       .UseEnvironment("Testing")
       .UseApplicationPath("YourMvcApplication");
    var server = new TestServer(builder);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-26
      • 2016-11-03
      • 1970-01-01
      相关资源
      最近更新 更多