我尝试按照以下教程实施我的应用程序的集成测试:https://docs.microsoft.com/en-us/aspnet/core/testing/integration-testing
public class CreditCardApplicationShould
{
[Fact]
public async Task RenderApplicationForm()
{
var builder = new WebHostBuilder()
.UseContentRoot(@"C:\Users\usuario\source\repos\CreditCardApp\CreditCardApp")
.UseEnvironment("Development")
.UseStartup<CreditCardApp.Startup>()
.UseApplicationInsights();
var server = new TestServer(builder);
var client = server.CreateClient();
var response = await client.GetAsync("/Apply/Index");
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
Assert.Contains("New Credit Card Application", responseString);
}
}
但是,当我尝试运行集成测试时,它会给我以下错误:
&#34;消息:System.InvalidOperationException:视图&#39;索引&#39;不是 找到。搜索了以下位置: /Views/Apply/Index.cshtml /Views/Shared/Index.cshtml"
将集成测试与MVC应用程序分离似乎是一个常见问题。
这里也是startup.cs
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
CurrentEnvironment = env;
}
public IConfiguration Configuration { get; }
private IHostingEnvironment CurrentEnvironment { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddApplicationPart(typeof(ApplyController).GetTypeInfo().Assembly);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
我发现了一些解决方法,即在Startup.cs中包含AddApplicationPart,但它仍无效。
我不确定它是否无法正常工作,因为我使用的是.NET Core 2.0。我很感激任何提示。
答案 0 :(得分:1)
我有类似的问题,我通过向appsettings.json
添加WebHostBuilder()
文件路径解决了这个问题。我实施了如下。
var builder = new WebHostBuilder()
.UseContentRoot(@"C:\Users\usuario\source\repos\CreditCardApp\CreditCardApp")
.UseEnvironment("Development")
.UseStartup<CreditCardApp.Startup>()
.UseApplicationInsights()
.UseConfiguration(new ConfigurationBuilder()
.SetBasePath(YourProjectPath) // @"C:\Users\usuario\source\repos\CreditCardApp\CreditCardApp"
.AddJsonFile("appsettings.json")
.Build()
);