【发布时间】:2021-07-05 17:40:00
【问题描述】:
我正在尝试使用 NUnit 为我的 .NET 核心 API 创建一个集成测试项目。
我在尝试 API 调用时遇到异常 404。
我为我的测试创建了 FakeStartup 类。如果我的启动它只是一个副本。
注意:- 如果我通过了我的 IntegrationTestFactory 的 Startup 类,它可以正常工作而没有问题。
私有只读IntegrationTestFactory factory = new();
public class IntegrationTestFactory<TTestStartup> : WebApplicationFactory<TTestStartup> where TTestStartup : class
{
protected override IHostBuilder CreateHostBuilder()
{
var host = Host.CreateDefaultBuilder()
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<TTestStartup>();
webBuilder.UseEnvironment("Development");
})
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration));
return host;
}
}
下面是我的测试课
[TestFixture]
public class SimpleIntegrationTests
{
private readonly IntegrationTestFactory<FakeStartup> factory = new();
[Test]
public async Task SimpleTestCase()
{
var client = factory.CreateClient();
// Arrange
var faker = new Faker();
var password = $"{faker.Internet.Password(prefix: "TestPassword12@")}$"; //to satisfy the requirement for passwords
var mockData = new Faker<SaveUserCommand>()
.RuleFor(u => u.FirstName, f => f.Name.LastName(Name.Gender.Male))
.RuleFor(u => u.LastName, f => f.Name.LastName(Name.Gender.Male))
.RuleFor(u => u.EmailAddress, (f, u) => f.Internet.Email(u.FirstName, u.LastName))
.RuleFor(u => u.MobileNumber, f => f.Phone.PhoneNumberFormat(10))
.RuleFor(u => u.Password, password)
.RuleFor(u => u.ConfirmPassword, password)
.RuleFor(u => u.IsFromRegistrationPage, false)
.RuleFor(u => u.RoleType, f => f.PickRandom<RoleType>())
.RuleFor(u => u.PurposeType, f => f.PickRandom<PurposeType>());
var command = mockData.Generate();
var stringContent = new StringContent(command.ToJson(), Encoding.UTF8, "application/json");
var response = await client.PostAsync("/api/user", stringContent);
}
}
【问题讨论】:
标签: c# asp.net-core .net-core integration-testing nunit-3.0