Should I use AutoMapper in my unit tests?

I am writing unit tests for ASP.NET MVC controller methods.

These controllers are dependent on IMapper , the interface I created for the abstract AutoMapper passed through the constructor installation using Castle Windsor.

In action methods, IMapper used to map domain objects to ViewModel objects and vice versa, the purpose of which is to save DBMS and save action methods concisely.

In my unit tests, should I

  • Configure AutoMapper with the correct bindings (they are created using AutoMapper profiles that can be tested and reused between websites and unit test) and pass this as the correct implementation of AutoMapper IMapper .

  • Passing mock objects (I use Moq) for the IMapper instance, depending on the test (this would mean duplicating some work in the test setup code to make sure that the objects returned from mock mapper are related to the objects that the mocker displays for display).

  • Hand-configure AutoMapper using only the mappings that I think I will need for each test (a lot of work and tools, I don’t test the mappings that will really be used).

What is the opinion of using infrastructure code in unit tests? At what point will this become an integration test (i.e. Testing the integration of AutoMapper and my controllers)?

It seems like 2 is a purist view, although it seems to me that I need to learn more about Moq and how to get it to return values ​​related to the actual values ​​passed to the methods that it mocks.

+7
source share
2 answers

I could agree with No. 2. You know that Automapper works, you know what your injection work is (got the tests for this right? :-)). I would focus more on the specifics, things that are not just SomeClass.Property = AnotherClass.Property. THESE special cases should not be tested for basic copy functions. Do not test the framework.

As for the larger test code, I feel that everything is in order. Tests should be configured within the specified tests (also within reason) for this unit only.

As for Moq, the syntax is simple, don't overdo it. var obj = new Mock (); then set your properties as obj.Setup (x => x.Property). Returns ("hello") if you don't have a more specific problem? Moq also set all the properties on it, so you might not even need an automapper

-edit- found it, it is obj.SetupAllProperties ();

+6
source

I'm for # 2 like jeriley

Adding to Moq, if you need to return an object based on the values ​​passed to it, you can write your customization like this:

  mockObject.Setup (x => x.MapObject (It.IsAny ())
           .Returns ((ProductDto productDto) => 
            {
                var product = new Product ()
                {
                    Id = productDto.Id,
                    Name = productDto.Name
                };

                return product
            }); 

A bit messy, but comfortable.

+4
source

All Articles