我想實現我的應用程序的集成測試從教程如下:https://docs.microsoft.com/en-us/aspnet/core/testing/integration-testingASPNET核心集成測試返回404
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);
}
}
然而,當我試圖運行集成測試,它給了我出現以下錯誤:
"Message: System.InvalidOperationException : The view 'Index' was not found. The following locations were searched: /Views/Apply/Index.cshtml /Views/Shared/Index.cshtml"
將集成測試從MVC應用程序中分離出來似乎是一個常見問題。
這裏太
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,上面寫着包括在Startup.cs的AddApplicationPart,但它仍然沒有工作。
我不確定它是否工作,因爲我使用.NET Core 2.0。我很欣賞任何提示。
我認爲你需要驗證內容根路徑 – Nkosi
@Nkosi它不工作太。正如你所看到的,我很難編碼ContentRoot的路徑,甚至沒有成功... –
看看如何在這裏設置路徑https://stackoverflow.com/a/37844252/5233410 – Nkosi