简体   繁体   English

xUnit测试和.NET Core 2.0中的自动映射

[英]Automapper in xUnit testing and .NET Core 2.0

I have .NET Core 2.0 Project which contains Repository pattern and xUnit testing. 我有.NET Core 2.0项目,其中包含存储库模式和xUnit测试。

Now, here is some of it's code. 现在,这里有一些代码。

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);
    }
}

My Test Class: 我的测试班:

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);
        }
    }
}

Issue I Am facing. 我面临的问题。

My Issue is that when I run this code with database context and execute Get() method, it works fine, it gives me all results. 我的问题是,当我使用数据库上下文运行此代码并执行Get()方法时,它工作正常,它给了我所有结果。

But when I tries to run test case, it's not returning any data of Dto object. 但是当我尝试运行测试用例时,它没有返回任何Dto对象的数据。 When I debugged I found that 当我调试时,我发现了

  1. I am getting my test object in controller using mockRepo . 我使用mockRepo在控制器中获取我的测试对象。

  2. But it looks like Auto mapper is not initialized correctly, because while mapping it's not returning anything in 但看起来Auto mapper没有正确初始化,因为虽然映射它没有返回任何内容

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

What I tried So Far? 我到底尝试了什么?

I followed all this answers but still it's not working. 我遵循了所有这些答案,但仍然无法正常工作。

Mocking Mapper.Map() in Unit Testing 在单元测试中模拟Mapper.Map()

How to Mock a list transformation using AutoMapper 如何使用AutoMapper模拟列表转换

So, I need help from someone who is good in xUnit and automapper, and need guidance on how to initialize mock Mapper correctly. 所以,我需要一些擅长xUnit和automapper的人的帮助,并且需要有关如何正确初始化mock Mapper的指导。

Finally it worked for me, I followed this way How to Write xUnit Test for .net core 2.0 Service that uses AutoMapper and Dependency Injection? 最后它对我有用 ,我按照这种方式如何编写xUnit Test for .net core 2.0 Service使用AutoMapper和依赖注入?

Here I am posting my answer and Test Class so if needed other SO's can use. 在这里,我发布我的答案和测试类,所以如果需要其他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);
        }
    }
}

I needed to inject IMapper , use ProjectTo to get a mapped IQueryable , then implement some more logic on the queryable after the map. 我需要注入IMapper ,使用ProjectTo获取映射的IQueryable ,然后在map之后在queryable上实现更多逻辑。 So here's what I did to mock it: 所以这就是我做的嘲笑:

var models = new object[]
{
    ⋮
}.AsQueryable();
var mapper = new Mock<IMapper>();
mapper.Setup(x => x.ProjectTo(
        It.IsAny<IQueryable>(),
        It.IsAny<object>(),
        It.IsAny<Expression<Func<object, object>>[]>()))
    .Returns(models);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM