集成测试EF Core + AutoMapper ProjectTo

时间:2019-01-30 23:19:26

标签: c# entity-framework-core automapper

我正在尝试集成测试使用AutoMapper和ProjectTo扩展方法的服务类。在应用程序本身中,我正在通过ASP.Net Core的内置DI框架注入IMapper。随着应用本身的工作,所有这些似乎都已正确配置。例如,我的服务类类似于此

public class MyServiceClass
{
    private readonly IMapper _mapper;
    private readonly MyDbContext _context;
    public MyServiceClass(IMapper mapper, MyDbContext context)
    {
        _mapper = mapper;
        _context = context;
    }

    public MyModelDto GetMyModel()
    {
        var myModelDto = _context.MyModels.ProjectTo<MyModelDto>().FirstOrDefault();
        return myModelDto;
    }
}

现在,我想对该服务进行集成测试,即在Xunit测试中对其进行新的测试(由于它是一个单元测试项目,因此无需ASP.Net DI框架),并使其实际上针对一个测试数据库运行查询。我的单元测试看起来像这样

public class MyServiceClassTests
{
    [Fact]
    public void GetMyModelTest()
    {
        // Arrange
        var context = new MyDbContext();
        var config = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile<MyModelProfile>();
        });
        var mapper = new Mapper(config);
        var sut = new MyServiceClass(mapper, context);

        // Act
        var results = sut.GetMyModel();

        // Assert
        Assert.NotNull(results);
    }
}

我收到以下异常:

Error Message:
 System.InvalidOperationException : Mapper not initialized.
 Call Initialize with appropriate configuration. 
If you are trying to use mapper instances through a container or otherwise,
 make sure you do not have any calls to the static Mapper.Map methods,
 and if you're using ProjectTo or UseAsDataSource extension methods,
 make sure you pass in the appropriate IConfigurationProvider instance.

强调如果您使用的是ProjectTo或UseAsDataSource扩展方法,请确保传递适当的IConfigurationProvider实例。

当然,我不想更改所有对ProjectTo <>的使用以传递IConfigurationProvider,我想继续使用无参数版本。当我在单元测试中构造自己的IMapper实例时,services.AddAutoMapper()扩展正在执行的操作无法复制。

我能做些什么以使它按照我认为应该起作用的方式进行吗?

0 个答案:

没有答案