如何解决 ASP .NET 集成测试中的可访问性参数不一致?

问题描述 投票:0回答:1

我正在尝试为 ASP .NET WebApi 进行干净的集成测试。

这是Web应用程序工厂类。 它在扩展中使用的程序类是 api 项目的内部类。 (使用 InternalsVisibleTo 完成)

internal class DozerWebApplicationFactory : WebApplicationFactory<Program>
{
    //Omitted not useful
}

在测试中我可以这样做:

public class QuotesControllerTests
{

    private readonly DozerWebApplicationFactory _application;
    private readonly HttpClient _httpClient;

    public QuotesControllerTests()
    {
        // Arrange/Setup
        _application = new DozerWebApplicationFactory();
        _httpClient = _application.CreateClient();
    }


}

但我想使用 IClassFixture 类来做到这一点:

public class QuotesControllerTests : IClassFixture<DozerWebApplicationFactory>
{

    private readonly DozerWebApplicationFactory _application;
    private readonly HttpClient _httpClient;

    public QuotesControllerTests(DozerWebApplicationFactory application)
    {
        // It doesn't work because this constructor is public (tests need to be public) but the Factory is internal due to program being internal as stated above.
        _application = application;
        _httpClient = _application.CreateClient();
    }


}

然而,最后一种方法并不是因为这个构造函数是公共的(测试需要是公共的),而是工厂是内部的,因为程序是内部的,如上所述。

CS0051    Inconsistent accessibility: parameter type 'DozerWebApplicationFactory' is less accessible than method 'QuotesControllerTests.QuotesControllerTests(DozerWebApplicationFactory)'

我该怎么做才能使其与 IClassFixture 一起工作?

c# asp.net api testing integration-testing
1个回答
0
投票

一个选项是在测试项目中创建一种“持有者” - 它可以是公共类,但包含对内部类的引用:

public class DozerFactoryHolder
{
    internal DozerWebApplicationFactory Factory { get; set; }
}

然后可以将其用作类型参数和构造函数参数:

public class QuotesControllerTests : IClassFixture<DozerFactoryHolder>
{
    private readonly DozerWebApplicationFactory _application;

    public QuotesControllerTests(DozerFactoryHolder holder)
    {
        _application = holder.Factory;
        ...
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.