相关疑难解决方法(0)

NET NET:在Xunit Test中为AppService,存储库等执行所有依赖注入

我正在尝试在XUnit测试中为AppService实现依赖注入。理想的目标是运行原始应用程序启动/配置,并使用启动中的任何依赖项注入,而不是在测试中再次重新初始化所有DI,这就是整个目标。

更新:Mohsen的答案很接近。需要更新几个语法/要求错误才能起作用。

由于某种原因,原始应用程序可以工作,并且可以致电Department App Service。但是,它无法在Xunit中调用。最终使Testserver在原始应用程序中使用Startup和Configuration进行工作。现在收到以下错误:

Message: The following constructor parameters did not have matching fixture data: IDepartmentAppService departmentAppService

namespace Testing.IntegrationTests
{
    public class DepartmentAppServiceTest
    {
        public DBContext context;
        public IDepartmentAppService departmentAppService;

        public DepartmentAppServiceTest(IDepartmentAppService departmentAppService)
        {
            this.departmentAppService = departmentAppService;
        }

        [Fact]
        public async Task Get_DepartmentById_Are_Equal()
        {
            var options = new DbContextOptionsBuilder<SharedServicesContext>()
                .UseInMemoryDatabase(databaseName: "TestDatabase")
                .Options;
            context = new DBContext(options);

            TestServer _server = new TestServer(new WebHostBuilder()
                .UseContentRoot("C:\\OriginalApplication")
                .UseEnvironment("Development")
                .UseConfiguration(new ConfigurationBuilder()
                    .SetBasePath("C:\\OriginalApplication")
                    .AddJsonFile("appsettings.json")
                    .Build()).UseStartup<Startup>());

            context.Department.Add(new Department { DepartmentId = 2, DepartmentCode = "123", DepartmentName …
Run Code Online (Sandbox Code Playgroud)

.net c# xunit .net-core asp.net-core

12
推荐指数
3
解决办法
1758
查看次数

使用XUnit和ASP.NET Core 1.0进行依赖注入

我试图找出如何使用XUnit的依赖注入.我的目标是能够将我的ProductRepository注入我的测试类.

这是我正在尝试的代码:

public class DatabaseFixture : IDisposable
{
    private readonly TestServer _server;

    public DatabaseFixture()
    {
        _server = new TestServer(TestServer.CreateBuilder().UseStartup<Startup>());
    }

    public void Dispose()
    {
        // ... clean up test data from the database ...
    }
}

public class MyTests : IClassFixture<DatabaseFixture>
{
    DatabaseFixture _fixture;
    public ICustomerRepository _repository { get; set; }

    public MyTests(DatabaseFixture fixture, ICustomerRepository repository)
    {
        _fixture = fixture;
        _repository = repository;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是错误: 以下构造函数参数没有匹配的fixture数据(ICustomerRepository存储库)

这让我相信XUnit不支持依赖注入,只有它是一个Fixture.

有人能给我一种使用XUnit在我的测试类中获取ProductRepository实例的方法吗?我相信我正确启动了测试服务器,因此Startup.cs运行并配置DI.

c# asp.net xunit asp.net-core asp.net-core-1.0

8
推荐指数
1
解决办法
5994
查看次数

标签 统计

asp.net-core ×2

c# ×2

xunit ×2

.net ×1

.net-core ×1

asp.net ×1

asp.net-core-1.0 ×1