集成测试给出编译错误 CS0051

r .*_* .r 4 c# integration-testing asp.net-core asp.net-core-webapi

我正在使用 ASP.NET 6 Core 并为使用模拟DBContext. 尝试以Microsoft 文档为基础。但我无法建造,因为我正在得到

CS0051 可访问性不一致:参数类型“CustomWebApplicationFactory<Program>”比方法“ProjectsControllerTests.ProjectsControllerTests(CustomWebApplicationFactory<Program>)”的可访问性较差

但他们都是公开的?!

项目控制器测试.cs

public class ProjectsControllerTests
    {
        private readonly CustomWebApplicationFactory<Program> _factory;
        private const string s_apiBaseUri = "/api/v1";

        public ProjectsControllerTests(CustomWebApplicationFactory<Program> factory)
        {
            // Arrange
            _factory = factory;
        }

        [Fact]
        public async Task Post_Responds201IfAuthenticatedAndRequiredFields_SuccessAsync()
        {
            // Arrange
            HttpClient? client = _factory.CreateClient(new WebApplicationFactoryClientOptions()
            {
                AllowAutoRedirect = false
            });

            var project = new Project() { Name = "Test Project" };
            var httpContent = new StringContent(JsonSerializer.Serialize(project));

            // Act
            var response = await client.PostAsync($"{s_apiBaseUri}/projects", httpContent);

            // Assert
            Assert.Equal(System.Net.HttpStatusCode.Created, response.StatusCode);
        }
    }
Run Code Online (Sandbox Code Playgroud)

CustomWebApplicationFactory.cs

public class CustomWebApplicationFactory<TStartup>
        : WebApplicationFactory<TStartup> where TStartup : class
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                var descriptor = services.SingleOrDefault(
                    d => d.ServiceType ==
                        typeof(DbContextOptions<myDbContext>));

                if (descriptor != null)
                    services.Remove(descriptor);

                services.AddDbContext<myDbContext>(options =>
                {
                    options.UseInMemoryDatabase("InMemoryDbForTesting");
                });

                services.AddAuthentication("Test")
                .AddScheme<AuthenticationSchemeOptions, MockAuthHandler>(
                    "Test", options => { });

                var sp = services.BuildServiceProvider();

                using (var scope = sp.CreateScope())
                {
                    var scopedServices = scope.ServiceProvider;
                    var db = scopedServices.GetRequiredService<myDbContext>();
                    var logger = scopedServices
                        .GetRequiredService<ILogger<CustomWebApplicationFactory<Program>>>();

                    db.Database.EnsureCreated();

                    try
                    {
                        db.EndUsers.Add(new DataAccessLibrary.Models.EndUser() { ObjectIdentifier = "test-oid" });
                        db.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, "An error occurred seeding the " +
                            "database with test messages. Error: {Message}", ex.Message);
                    }
                }
            });
        }
    }
Run Code Online (Sandbox Code Playgroud)

r .*_* .r 8

该类Program在 ASP.NET 6 Core 中不是公共的。根据https://learn.microsoft.com/en-us/aspnet/core/migration/50-to-60-samples?view=aspnetcore-6.0#twa您可以Program通过将以下内容附加到 Program.cs 来公开:

public partial class Program { }
Run Code Online (Sandbox Code Playgroud)

还需要注意的是,上面的测试类必须定义为:

public class ProjectsControllerTests : IClassFixture<CustomWebApplicationFactory<Program>>
Run Code Online (Sandbox Code Playgroud)

让 DI 发挥作用。