【问题标题】:How to Write xUnit Test for .net core 2.0 Service that uses AutoMapper and Dependency Injection? [closed]如何为使用 AutoMapper 和依赖注入的 .net core 2.0 服务编写 xUnit 测试? [关闭]
【发布时间】:2018-09-17 10:22:52
【问题描述】:

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

我有以下服务类,它使用依赖注入来获取 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 编写单元测试,并让我的测试类提供 IMapper 实现和 ISubmissionCategoryRepository 实现。

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

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

【问题讨论】:

  • 唉,要求站外资源被认为是题外话。
  • 使用模拟库,您可以模拟接口,将它们注入到被测对象中,并运行被测方法以断言其行为符合预期。
  • 显示您是如何尝试测试上述代码的。从那里我们应该能够引导您朝着正确的方向前进。
  • 这是一个接近您所要求的示例stackoverflow.com/a/48387824/5233410
  • 已编辑问题以删除对书籍或教程的明确请求。 另请注意,它生成了一个可接受的高质量答案,其中不包含任何此类建议。应该重新打开。

标签: c# unit-testing automapper asp.net-core-2.0 xunit


【解决方案1】:

这个 sn-p 应该为您提供一个先机:

[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
}

【讨论】:

  • 上面的 非常有帮助,足以向我展示如何编写单元测试。我确实需要添加);到配置语句的末尾
  • @junkangli 你能回答这个问题吗? stackoverflow.com/questions/57331395/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 2020-06-30
  • 2020-06-30
  • 2018-03-03
  • 2018-08-23
  • 2018-02-20
相关资源
最近更新 更多