c# - xUnit 测试和 .NET Core 2.0 中的 Automapper

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

我有 .NET Core 2.0 项目,其中包含存储库模式和 xUnit 测试。

现在,这是它的一些代码。

Controller :

public class SchedulesController : Controller
{
    private readonly IScheduleRepository repository;
    private readonly IMapper mapper;

    public SchedulesController(IScheduleRepository repository, IMapper mapper)
    {
        this.repository = repository;
        this.mapper = mapper;
    }

    [HttpGet]
    public IActionResult Get()
    {
        var result = mapper.Map<IEnumerable<Schedule>, IEnumerable<ScheduleDto>>(source: repository.items);
        return new OkObjectResult(result);
    }
}

我的测试类:

public class SchedulesControllerTests
{
    [Fact]
    public void CanGet()
    {
        try
        {
            //Arrange
            Mock<IScheduleRepository> mockRepo = new Mock<IScheduleRepository>();
            mockRepo.Setup(m => m.items).Returns(new Schedule[]
            {
                new Schedule() { Id=1, Title = "Schedule1" },
                new Schedule() { Id=2, Title = "Schedule2" },
                new Schedule() { Id=3, Title = "Schedule3" }
            });

            var mockMapper = new Mock<IMapper>();
            mockMapper.Setup(x => x.Map<Schedule>(It.IsAny<ScheduleDto>()))
                .Returns((ScheduleDto source) => new Schedule() { Title = source.Title });

            SchedulesController controller = new SchedulesController(repository: mockRepo.Object, mapper: mockMapper.Object);

            //Act
            var result = controller.Get();

            //Assert
            var okResult = result as OkObjectResult;
            Assert.NotNull(okResult);

            var model = okResult.Value as IEnumerable<ScheduleDto>;
            Assert.NotNull(model);

        }
        catch (Exception ex)
        {
            //Assert
            Assert.False(false, ex.Message);
        }
    }
}

我面临的问题。

我的问题是,当我使用数据库上下文运行此代码并执行 Get() 时方法,它工作正常,它给了我所有的结果。

但是当我尝试运行测试用例时,它没有返回 Dto 对象的任何数据。 当我调试时我发现

  1. 我正在使用 mockRepo 在 Controller 中获取我的测试对象.

  2. 但看起来自动映射器没有正确初始化,因为在映射时它没有返回任何东西

    var result = mapper.Map<IEnumerable<Schedule>, IEnumerable<ScheduleDto>>(source: repository.items);

到目前为止我尝试了什么?

我遵循了所有这些答案,但仍然无法正常工作。

Mocking Mapper.Map() in Unit Testing

How to Mock a list transformation using AutoMapper

因此,我需要精通 xUnit 和 automapper 的人的帮助,并且需要有关如何正确初始化 mock Mapper 的指导。

最佳答案

最后它对我有用,我按照这种方式How to Write xUnit Test for .net core 2.0 Service that uses AutoMapper and Dependency Injection?

我在这里发布我的答案和测试类,如果需要其他 SO 可以使用。

public class SchedulesControllerTests
{
    [Fact]
    public void CanGet()
    {
        try
        {
            //Arrange
            //Repository
            Mock<IScheduleRepository> mockRepo = new Mock<IScheduleRepository>();
            var schedules = new List<Schedule>(){
                new Schedule() { Id=1, Title = "Schedule1" },
                new Schedule() { Id=2, Title = "Schedule2" },
                new Schedule() { Id=3, Title = "Schedule3" }
            };

            mockRepo.Setup(m => m.items).Returns(value: schedules);

            //auto mapper configuration
            var mockMapper = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new AutoMapperProfile());
            });
            var mapper = mockMapper.CreateMapper();

            SchedulesController controller = new SchedulesController(repository: mockRepo.Object, mapper: mapper);

            //Act
            var result = controller.Get();

            //Assert
            var okResult = result as OkObjectResult;
            if (okResult != null)
                Assert.NotNull(okResult);

            var model = okResult.Value as IEnumerable<ScheduleDto>;
            if (model.Count() > 0)
            {
                Assert.NotNull(model);

                var expected = model?.FirstOrDefault().Title;
                var actual = schedules?.FirstOrDefault().Title;

                Assert.Equal(expected: expected, actual: actual);
            }
        }
        catch (Exception ex)
        {
            //Assert
            Assert.False(false, ex.Message);
        }
    }
}

关于c# - xUnit 测试和 .NET Core 2.0 中的 Automapper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49934707/

相关文章:

javascript - 如何使用 Jasmine 为 $resource (AngularJS) 定义测试

c# - 使用 C# AutoMapper 将 DateTime UTC 转换为本地

c# - 如何将字符串映射到自动映射器中的日期?

c# - WPF 从代码触发动画

javascript - 使用 jquery 添加元素到空列表

javascript - ES6 [Symbol.iterator] 不是带数组的函数

automapper - 必须解析为顶级成员

c# - MassTransit:将 header 添加到发布管道

c# - 为什么从查询字符串中删除反斜杠 - ASP.NET 和 Javascript

java - 线程安全单元测试