After using Automapper to map a ViewModel how and what should I test?

前端 未结 2 1902
后悔当初
后悔当初 2021-01-31 12:11

I am attempting to test the Index action of a controller. The action uses AutoMapper to map a domain Customer object to a view model TestCustomer

2条回答
  •  日久生厌
    2021-01-31 13:06

    I would probably separate the coupling between AutoMapper and the controller by introducing an abstraction:

    public interface IMapper
    {
        TDest Map(TSource source);
    }
    
    public CustomerToTestCustomerFormMapper: IMapper
    {
        static CustomerToTestCustomerFormMapper()
        {
            // TODO: Configure the mapping rules here
        }
    
        public TestCustomerForm Map(Customer source)
        {
            return Mapper.Map(source);
        }
    }
    

    Next you pass this into the controller:

    public HomeController: Controller
    {
        private readonly IMapper _customerMapper;
        public HomeController(IMapper customerMapper)
        {
            _customerMapper = customerMapper;
        }
    
        public ActionResult Index()
        {
            TestCustomerForm cust = _customerMapper.Map(
                _repository.GetCustomerByLogin(CurrentUserLoginName)
            );
            return View(cust);
        }
    }
    

    And in your unit test you would use your favorite mocking framework to stub this mapper.

提交回复
热议问题