如何为使用 AutoMapper 和依赖注入的 .net core 2.0 服务编写 xUnit 测试?

How to Write xUnit Test for .net core 2.0 Service that uses AutoMapper and Dependency Injection?

我是 .net 新手core/C# 编程(来自 Java)

我有以下服务class,它使用依赖注入来获取 AutoMapper 对象和数据存储库对象,用于创建 SubmissionCategoryViewModel 对象的集合:

public class SubmissionCategoryService : ISubmissionCategoryService
{

    private readonly IMapper _mapper;

    private readonly ISubmissionCategoryRepository _submissionCategoryRepository;

    public SubmissionCategoryService(IMapper mapper, ISubmissionCategoryRepository submissionCategoryRepository)
    {

        _mapper = mapper;

        _submissionCategoryRepository = submissionCategoryRepository;

    }

    public List<SubmissionCategoryViewModel> GetSubmissionCategories(int ConferenceId)
    {


        List<SubmissionCategoryViewModel> submissionCategoriesViewModelList = 
            _mapper.Map<IEnumerable<SubmissionCategory>, List<SubmissionCategoryViewModel>>(_submissionCategoryRepository.GetSubmissionCategories(ConferenceId) );

        return submissionCategoriesViewModelList;


    }
}

我正在使用 Xunit 编写我的单元测试。我不知道如何为方法 GetSubmissionCategories 编写单元测试并让我的测试 class 提供 IMapper 实现和 ISubmissionCategoryRepository 实现。

到目前为止,我的研究表明我可以创建依赖对象的测试实现(例如 SubmissionCategoryRepositoryForTesting),或者我可以使用模拟库来创建依赖接口的模拟。

但我不知道如何创建 AutoMapper 的测试实例或 AutoMapper 的模拟。

此代码段应为您提供先机:

[Fact]
public void Test_GetSubmissionCategories()
{
    // Arrange
    var config = new MapperConfiguration(cfg =>
    {
        cfg.AddProfile(new YourMappingProfile());
    });
    var mapper = config.CreateMapper();
    var repo = new SubmissionCategoryRepositoryForTesting();
    var sut = new SubmissionCategoryService(mapper, repo);

    // Act
    var result = sut.GetSubmissionCategories(ConferenceId: 1);

    // Assert on result
}