Mapper未初始化,我的单元测试错误Core.Net 2.0

时间:2017-11-25 01:48:43

标签: c# testing .net-core automapper

我在Core.net 2.0中使用UOW和automapper完成了WebApi。 一切都运行正常,但现在我想用Nunit实现单元测试,我有自动缓冲区的这个错误

  

消息:System.InvalidOperationException:Mapper未初始化。   使用适当的配置调用Initialize。如果你想   通过容器或其他方式使用mapper实例,确保你   没有任何对静态Mapper.Map方法的调用,如果你是   使用ProjectTo或UseAsDataSource扩展方法,请确保您   传入适当的IConfigurationProvider实例。

我该如何解决这个问题。提前致谢 。 Jolynice

类AutoMapperProfile.cs

public class AutoMapperProfile : Profile
{
    public AutoMapperProfile()
    {
        CreateMap<Cars, CarsDTO>()
            .ReverseMap();
    }
}

类Startup.cs

public class Startup
{
    public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    public void ConfigureServices(IServiceCollection services)
    {

        //removed configurations 

        // Add cors
        services.AddCors();

        // Add framework services.
        services.AddMvc();

        Mapper.Initialize(cfg =>
        {
            cfg.AddProfile<AutoMapperProfile>();
        });

        // Repositories
        services.AddScoped<IUnitOfWork, HttpUnitOfWork>();
        services.AddScoped<IAccountManager, AccountManager>();
    }
}

class carsController.cs

[Authorize]
[Route("api/[controller]")]
public class CarsController : Controller
{
private IUnitOfWork _unitOfWork;
readonly ILogger _logger;
private readonly IAccountManager _accountManager;

public CarsController(
    IUnitOfWork unitOfWork,
    ILogger<CarsController> logger, 
    IAccountManager accountManager)
{
    _unitOfWork = unitOfWork;
    _logger = logger;
    _accountManager = accountManager;
}


[HttpGet]
public IActionResult GetAll()
{
    var allCars = _unitOfWork.CarsRepository.GetAllCarsData();
    if (allCars == null)
    {
        return NotFound();
    }
    return Ok(Mapper.Map<IEnumerable<CarsDTO>>(allCars));
}

这是我的单元测试

[TestFixture]
public class CarsControllerTest
{
#region private variables
List<Cars> cars = new List<Cars>();

CarsController _carsController = null;
IUnitOfWork _unitOfWork;
ICarsRepository _carsRepository;
#endregion


[SetUp]
public void SetUp()
{
    cars = new List<Cars>
    {
     new Cars
    {
        Alias = "406Moq",
        BrandId = 1,
        ModelId = 1,
        Plate = "00-00-01",
        AltranVehicle = 0,
        DefaultCar = 0,
        Active = 1,
        ColorId = 1
    }
    };
}


[Test]
public void GetAllCarsControllerTest()
{
    //Arrange
    _carsRepository = SetupCarsRepository();
    var unityOfWork = new Mock<IUnitOfWork>();
    var _logger = new Mock<ILogger<CarsController>>();
    var accountManager = new Mock<IAccountManager>();

    unityOfWork.SetupGet(c => c.CarsRepository).Returns(_carsRepository);
    _unitOfWork = unityOfWork.Object;

    _carsController = new CarsController(_unitOfWork, _logger.Object, accountManager.Object);


    //Act
    var carsResult = _carsController.GetAll();

    //Assert
    carsResult.StatusCode.Should().Be(HttpStatusCode.OK);
}

private ICarsRepository SetupCarsRepository()
{
    //initialize  repository
    var mockRepo = new Mock<ICarsRepository>(MockBehavior.Default);

    //Setup mocking behavior
    mockRepo.Setup(c => c.GetAllCarsData()).Returns(cars);

    return mockRepo.Object;
}

//Cleanup
[TearDown]
public void TearDown()
{
    cars = null;
}
}
}

1 个答案:

答案 0 :(得分:19)

您在单元测试中缺少初始化映射器。以下内容在CarsControllerTest类构造函数中初始化映射器。

[TestFixture]
public class CarsControllerTest
{
    public CarsControllerTest()
    {
        Mapper.Initialize(cfg =>
        {
            cfg.AddProfile<AutoMapperProfile>();
        });
    }
}