为ASP .NET MVC创建单元测试时遇到的问题

时间:2016-10-05 01:52:39

标签: c# asp.net-mvc unit-testing automapper justmock

我正在为我的ASP .NET MVC Controller类创建一些单元测试,我遇到了一些非常奇怪的错误:

我的控制器代码如下:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(JournalViewModel journal)
{
    var selectedJournal = Mapper.Map<JournalViewModel, Journal>(journal);

    var opStatus = _journalRepository.DeleteJournal(selectedJournal);
    if (!opStatus.Status)
        throw new System.Web.Http.HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));

    return RedirectToAction("Index");
}

我的测试代码如下:

[TestMethod]
public void Delete_Journal()
{
    // Arrange

    // Simulate PDF file
    HttpPostedFileBase mockFile = Mock.Create<HttpPostedFileBase>();
    Mock.Arrange(() => mockFile.FileName).Returns("Test.pdf");
    Mock.Arrange(() => mockFile.ContentLength).Returns(255);

    // Create view model to send.
    JournalViewModel journalViewModel = new JournalViewModel();
    journalViewModel.Id = 1;
    journalViewModel.Title = "Test";
    journalViewModel.Description = "TestDesc";
    journalViewModel.FileName = "TestFilename.pdf";
    journalViewModel.UserId = 1;
    journalViewModel.File = mockFile; // Add simulated file

    Mock.Arrange(() => journalRepository.DeleteJournal(null)).Returns(new OperationStatus
    {
        Status = true
    });

    // Act
    PublisherController controller = new PublisherController(journalRepository, membershipRepository);
    RedirectToRouteResult result = controller.Delete(journalViewModel) as RedirectToRouteResult;

    // Assert
    Assert.AreEqual(result.RouteValues["Action"], "Index");
}

问题1 - 映射例外:

每次运行测试时,我都会收到以下异常:

  

测试名称:Delete_Journal测试
  FullName:Journals.Web.Tests.Controllers.PublisherControllerTest.Delete_Journal
  测试源:\ Source \ Journals.Web.Tests \ Controllers \ PublisherControllerTest.cs   :第132行   测试结果:测试持续时间失败:0:00:00,3822468

     

结果StackTrace:at   Journals.Web.Controllers.PublisherController.Delete(JournalViewModel   期刊)   \ Source \ Journals.Web \ Controllers \ PublisherController.cs:第81行   Journals.Web.Tests.Controllers.PublisherControllerTest.Delete_Journal()   在   \来源\ Journals.Web.Tests \ \控制器PublisherControllerTest.cs:行   156结果消息:测试方法   Journals.Web.Tests.Controllers.PublisherControllerTest.Delete_Journal   引发异常:AutoMapper.AutoMapperMappingException:缺少类型   地图配置或不支持的映射。

     

映射类型:JournalViewModel - &gt;日志   Journals.Model.JournalViewModel - &gt; Journals.Model.Journal

     

目的地路径:期刊

     

来源值:Journals.Model.JournalViewModel

似乎类JournalViewModelJournal之间存在映射问题,但我不知道它在哪里。我已将此代码添加到Application_Start中的Global.asax.cs

Mapper.CreateMap<Journal, JournalViewModel>();
Mapper.CreateMap<JournalViewModel, Journal>();

JournalJournalViewModel的映射正在发挥作用。

最后,我尝试添加Mapper.CreateMap<JournalViewModel, Journal>();作为Delete方法的第一行,然后一切正常,但我不确定原因。

问题2 - HTML异常

使用上面的解决方法运行映射后,我遇到一个问题,即Status中的属性var opStatus = _journalRepository.DeleteJournal(selectedJournal);始终为false,即使我使用Mock覆盖它并使其始终为true。这会导致抛出不应发生的HTML异常。

修改

我在Application_Start中更改为:

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<Journal, JournalViewModel>();
    cfg.CreateMap<JournalViewModel, Journal>();
});

但我仍然有同样的错误。

编辑 - 问题2已解决

事实证明我忘了将映射添加到我的单元测试类中,所以我做了以下内容:

[TestInitialize]
public void TestSetup()
{
    // Create necessary mappings
    Mapper.CreateMap<Journal, JournalViewModel>();
    Mapper.CreateMap<JournalViewModel, Journal>();

    //...other code omitted for brevity
}

事实证明,这是问题的根源。我认为,因为在单元测试中从不调用Global.asax.cs Application_Start(),所以从不创建Mapping,所以我必须在单元测试初始化​​中自己完成。

1 个答案:

答案 0 :(得分:5)

问题1

Automapper同时拥有Static and Instance API。您应该考虑将实例API与IMapper一起使用,并将其注入您的控制器。

public class PublisherController : Controller {
    private readonly IMapper mapper;

    public PublisherController(IJournalRepository journalRepository, IMembershipRepositry membershipRepository, IMapper mapper) {
        //...other code omitted for brevity
        this.mapper = mapper;
    }

    //...other code omitted for brevity

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Delete(JournalViewModel journal) {
        var selectedJournal = mapper.Map<JournalViewModel, Journal>(journal);

        var opStatus = _journalRepository.DeleteJournal(selectedJournal);
        if (!opStatus.Status)
            throw new System.Web.Http.HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));

        return RedirectToAction("Index");
    }
}

这样可以根据需要更好地模拟/伪装/配置映射。您应该确保将IMapper配置为依赖注入控制器。

如果您无法更改为实例api,那么您需要确保在运行测试之前映射器是Initialize

Mapper.Initialize(cfg => {
    cgf.CreateMap<JournalViewModel, Journal>();
});

问题2

你在测试中的安排是

Mock.Arrange(() => journalRepository.DeleteJournal(null)).Returns(new OperationStatus
{
    Status = true
});

这是因为您意识到不适用于使用实际实例调用journalRepository.DeleteJournal的情况。假设你正在使用来自Telerik的JustMock,你应该安排一个更灵活的论点。

Mock.Arrange(() => journalRepository.DeleteJournal(Arg.IsAny<Journal>())).Returns(new OperationStatus
{
    Status = true
});

来源:Handling Arguments in JustMock Arrangements

完成测试:实例API

[TestMethod]
public void Delete_Journal() {
    // Arrange

    //Configure mapping just for this test but something like this
    //should be in accessible from your composition root and called here.
    var config = new MapperConfiguration(cfg => {
        cfg.CreateMap<Journal, JournalViewModel>();
        cfg.CreateMap<JournalViewModel, Journal>();
    });

    var mapper = config.CreateMapper(); // IMapper

    // Simulate PDF file
    var mockFile = Mock.Create<HttpPostedFileBase>();
    Mock.Arrange(() => mockFile.FileName).Returns("Test.pdf");
    Mock.Arrange(() => mockFile.ContentLength).Returns(255);

    // Create view model to send.
    var journalViewModel = new JournalViewModel();
    journalViewModel.Id = 1;
    journalViewModel.Title = "Test";
    journalViewModel.Description = "TestDesc";
    journalViewModel.FileName = "TestFilename.pdf";
    journalViewModel.UserId = 1;
    journalViewModel.File = mockFile; // Add simulated file

    var status = new OperationStatus {
        Status = true
    };

    Mock.Arrange(() => journalRepository.DeleteJournal(Arg.IsAny<Journal>())).Returns(status);

    var controller = new PublisherController(journalRepository, membershipRepository, mapper);

    // Act        
    var result = controller.Delete(journalViewModel) as RedirectToRouteResult;

    // Assert
    Assert.AreEqual(result.RouteValues["Action"], "Index");
}

完成测试:静态API

[TestMethod]
public void Delete_Journal() {
    // Arrange

    //Configure mapping just for this test but something like this
    //should be in accessible from your composition root and called here.
    Mapper.Initialize(cfg => {
        cfg.CreateMap<Journal, JournalViewModel>();
        cfg.CreateMap<JournalViewModel, Journal>();
    });

    // Simulate PDF file
    var mockFile = Mock.Create<HttpPostedFileBase>();
    Mock.Arrange(() => mockFile.FileName).Returns("Test.pdf");
    Mock.Arrange(() => mockFile.ContentLength).Returns(255);

    // Create view model to send.
    var journalViewModel = new JournalViewModel();
    journalViewModel.Id = 1;
    journalViewModel.Title = "Test";
    journalViewModel.Description = "TestDesc";
    journalViewModel.FileName = "TestFilename.pdf";
    journalViewModel.UserId = 1;
    journalViewModel.File = mockFile; // Add simulated file

    var status = new OperationStatus {
        Status = true
    };

    Mock.Arrange(() => journalRepository.DeleteJournal(Arg.IsAny<Journal>())).Returns(status);

    var controller = new PublisherController(journalRepository, membershipRepository);

    // Act        
    var result = controller.Delete(journalViewModel) as RedirectToRouteResult;

    // Assert
    Assert.AreEqual(result.RouteValues["Action"], "Index");
}