I am a bit new to unit testing with xUnit, and I have some problems with AutoMapper. I am getting the Mapper already initialized issue.
I am using Automapper 8.0.0., ASP.NET Core 2.2 and xUnit 2.4.1.
I am writing unit tests for my controllers. I have unit tests in 3 different classes. Each class looks basically like this:
/* Constructor */
public ControllerGetTests()
{
/// Initialize AutoMapper
AutoMapper.Mapper.Reset();
MapperConfig.RegisterMaps();
/* Some mocking code here using Moq */
_controller = new MyController();
}
[Fact]
public async void Get_WhenCalled_ReturnsOkResult()
{
// Act
var okResult = await _controller.Get();
// Assert
Assert.IsType<OkObjectResult>(okResult);
}
/* etc. */
All three classes are similar and are basic tests for controllers. All controllers are using AutoMapper. I am using the same static class MapperConfig to register my mappings:
public static class MapperConfig
{
public static void RegisterMaps()
{
AutoMapper.Mapper.Initialize(config =>
{
config.CreateMap<SomeClass, SomeClassViewModel>();
config.CreateMap<SomeClassViewModel, SomeClass>();
});
}
}
I call this method in the constructor of each of the 3 test classes. Before calling it, I call the Mapper.Reset() - some answers here suggest that: Automapper - Mapper already initialized error
In the Test Explorer in VS when I select one test class and choose "Run selected tests", they all pass. However, when I select the main "Run all", some tests fail with the message Mapper already initialized. And each time it is different tests in different classes that fail.
I assume that different threads are created for different methods, but they are all trying to initialize the same mapper instance which throws an error.
However, I am not sure where am I supposed to call the initialization in one (and only one) place and have that same initialization be used for all my test classes (like I do in Startup.cs Configure method).
Thanks in advance.