lundi 25 juillet 2016

Unit Testing Controller that uses AutoMapper

I am attempting to Unit Test the following controller code in my MVC application.

    [AllowAnonymous]
    public ActionResult Index(string sort)
    {
      IEnumerable<Artist> artists;
      if (Request.IsAuthenticated)
      {
        artists = _artistService.GetArtistsForUser(User.Identity.GetUserId());
        if (!string.IsNullOrEmpty(sort) && sort != "asc")
        {
          ViewBag.Sort = "desc";
          artists = artists.OrderByDescending(a => a.FName);
        }
      }
      else
      {
        artists = _artistService.GetArtists(false);
        if (!string.IsNullOrEmpty(sort) && sort != "asc")
        {
          ViewBag.Sort = "desc";
          artists = artists.OrderByDescending(a => a.FName);
        }
      }

      var vm = new ArtistIndexVM { Artists = Mapper.Map<IEnumerable<Artist>, IEnumerable<ArtistVM>>(artists) };
      return View(vm);
    }

Notice that just before the final return statement, I have an AutoMapper mapping. This is throwing an error when I attempt to run the Unit Test. The error is

Test method Project.Controllers.ArtistControllerTests.Index_Get_ReturnsAViewResult threw exception: AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping.

What is the best way to resolve this without having to redefine the mappings once again in the Test Project? You know, in line with Don't Repeat Yourself (DRY) principles.

Aucun commentaire:

Enregistrer un commentaire