请注意,如果您尝试使用 xUnit 及其IClassFixture<T>
模式,如果您只使用 InternalsVisibleTo 方法,您将会遇到问题。具体来说,你会得到这样的结果:
“可访问性不一致:基类WebApplicationFactory<Program>
比课堂更难访问CustomWebApplicationFactory
."
当然你可以通过以下方式解决这个问题CustomWebApplicationFactory
内部,但它只会解决问题,因为现在您的单元测试类将给出相同的错误。当您尝试在那里更改它时,您会发现 xUnit 要求测试具有公共构造函数(而不是内部构造函数),并且您将被阻止。
该解决方案可以避免所有这些并允许您仍然使用IClassFixture<Program>
是为了使Program
类公开。显然,您可以通过摆脱 Program.cs 的神奇无类版本来做到这一点,但如果您不想完全更改该文件,您可以添加以下行:
public partial class Program { } // so you can reference it from tests
当然,一旦公开,您就可以在测试项目中使用它,并且一切正常。
顺便说一句,您通常更喜欢使用 IClassFixture 的原因是它允许您在测试类构造函数中仅设置一次 WebApplicationFactory,并获取一个HttpClient
您可以将其存储为字段的实例。这允许您的所有测试更短,因为它们只需要引用客户端实例,而不是工厂。
Example:
public class HomePage_Get : IClassFixture<CustomWebApplicationFactory>
{
private readonly HttpClient _client = new HttpClient();
public HomePage_Get(CustomWebApplicationFactory factory)
{
_client = factory.CreateClient();
}
[Fact]
public async Task IncludesWelcome()
{
HttpResponseMessage response = await _client.GetAsync("/");
response.EnsureSuccessStatusCode();
string stringResponse = await response.Content.ReadAsStringAsync();
Assert.Contains("Welcome.", stringResponse);
}
}
最后请注意Damian Edwards 的 MinimalAPIPlayground https://github.com/DamianEdwards/MinimalApiPlayground在我们讨论该问题后,已更新为使用此方法。看到这个commit https://github.com/DamianEdwards/MinimalApiPlayground/commit/2ffc975ee9eddc1587304bad8a88e5620860a392