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

Bru*_*ips 3 c# unit-testing xunit automapper asp.net-core-2.0

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

我有以下Service类,它使用依赖注入来获取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;


    }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用Xunit编写单元测试.我无法弄清楚如何编写方法GetSubmissionCategories一个单元测试,并有我的测试类提供一个IMapper实施和执行ISubmissionCategoryRepository.

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

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

如果你知道任何好的在线教程,详细介绍如何创建一个单元测试,其中被测试的类使用AutoMapper和依赖注入数据存储库,这将是伟大的.

感谢您的帮助.

jun*_*gli 14

这个片段应该为您提供一个先发制人:

[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
}
Run Code Online (Sandbox Code Playgroud)