[英]How to unit test startup.cs .Net Core
我的文章是對.NET Core中的單元測試Startup.cs文章的擴展
我試圖使用以下方法對類Startup.ca進行單元測試(與上一篇文章相同的代碼):
[TestMethod]
public void ConfigureServices_RegistersDependenciesCorrectly()
{
// Arrange
// Setting up the stuff required for Configuration.GetConnectionString("DefaultConnection")
Mock<IConfigurationSection> configurationSectionStub = new Mock<IConfigurationSection>();
configurationSectionStub.Setup(x => x["DefaultConnection"]).Returns("TestConnectionString");
Mock<Microsoft.Extensions.Configuration.IConfiguration> configurationStub = new Mock<Microsoft.Extensions.Configuration.IConfiguration>();
configurationStub.Setup(x => x.GetSection("ConnectionStrings")).Returns(configurationSectionStub.Object);
IServiceCollection services = new ServiceCollection();
var target = new Startup(configurationStub.Object);
// Act
target.ConfigureServices(services);
// Mimic internal asp.net core logic.
services.AddTransient<TestController>();
// Assert
var serviceProvider = services.BuildServiceProvider();
var controller = serviceProvider.GetService<TestController>();
Assert.IsNotNull(controller);
}
但是我在target.ConfigureServices(services)行出現了錯誤。 當我運行測試時。 我得到了錯誤:
消息:測試方法Project.Services.PublicReporting.Tests.StartupTests.ConfigureServices_RegistersDependencies正確拋出異常:System.IO.FileLoadException:無法加載文件或程序集'Microsoft.Extensions.Caching.Memory,版本= 2.1.2.0,Culture = neutral,PublicKeyToken = adb9793829ddae60'或其依賴項之一。 找到的程序集的清單定義與程序集引用不匹配。 (來自HRESULT的異常:0x80131040)---> System.IO.FileLoadException:無法加載文件或程序集“ Microsoft.Extensions.Caching.Memory,版本= 2.1.1.0,Culture = neutral,PublicKeyToken = adb9793829ddae60”或其中之一依賴。 找到的程序集的清單定義與程序集引用不匹配。 (來自HRESULT的異常:0x80131040)
這是因為我們正在調用ConfigureService,並且它在services.AddResponseCaching();中崩潰。
這是我的Configures Service方法,它作為第二行崩潰。
public void ConfigureServices(IServiceCollection services)
{
services.RegisterApplicationComponents();
services.AddResponseCaching();
}
我認為問題在於,當我們模擬該類時,我無法找到我們需要具有哪個正確的設置,以便AddResponseCaching()方法能夠通過。 是否有人知道configurationSectionStub.Setup中缺少的內容,還是我們需要模擬服務的行為?
謝謝!
在ASP.NET Core中使用集成測試,以確保Startup
基礎結構正常運行。 請注意,您可以通過在主機構建器上使用ConfigureTestServices
在測試中覆蓋treal服務來注入模擬服務。
[Fact]
public async Task Get_QuoteService_ProvidesQuoteInPage()
{
// Arrange
var client = _factory.WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(services =>
{
services.AddScoped<IQuoteService, TestQuoteService>();
});
})
.CreateClient();
//Act
var defaultPage = await client.GetAsync("/");
var content = await HtmlHelpers.GetDocumentAsync(defaultPage);
var quoteElement = content.QuerySelector("#quote");
// Assert
Assert.Equal("Something's interfering with time, Mr. Scarman, " +
"and time is my business.", quoteElement.Attributes["value"].Value);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.