The test method "X" threw an exception: System.InvalidOperationException: Mapper is not initialized. Initializing a call with the appropriate configuration

Here is the code for the method that I am developing unit test for:

public ActionResult ItemsListing() { var itemsList = itemsRepository.GetItems(true); if (itemsList.Count() > 0) { var itemsListVMs = Mapper.Map<IEnumerable<Item>, IEnumerable<itemsListingViewModel>>(itemsList); return View(itemsListVMs); } else { return RedirectToAction("Home"); } } 

The following is the code from the mapping configuration file:

 public static class MappingConfig { public static void RegisterMaps() { Mapper.Initialize(config => { config.CreateMap<Item, itemsListingViewModel>(); }); } } 

And I initialized mapper in the Application_Start() event of Global.asax , as shown below:

 MappingConfig.RegisterMaps(); 

The following is a simple verification method that I am trying to run:

 [TestMethod] public void ItemsListing() { HomeController controller = new HomeController(); ViewResult result = controller.ItemsListing() as ViewResult; Assert.IsNotNull(result); } 

It works great when I just run the application. But when I try to run the unit test method, it shows the specified error message. Can someone help me solve this problem? Thanks!

+5
source share
1 answer

You need to create / register mappings for unit tests, and Application_Start() will not execute. It is associated with IIS, which does not work during unit tests. You must manually call the mapping configurations.

 [TestClass] public class HomeControllerTests { [ClassInitialize] public static void Init(TestContext context) { MappingConfig.RegisterMaps(); } [TestMethod] public void ItemsListing() { HomeController controller = new HomeController(); ViewResult result = controller.ItemsListing() as ViewResult; Assert.IsNotNull(result); } } 

In the above test, the display configuration is done in a method decorated with the [ClassInitialize] attribute, which

ClassInitializeAttribute Class Defines a method that contains the code that should be used before the tests in the test class are executed and allocate resources for used by the test class.

+5
source

All Articles