1

I have following line of code in my controller and need to Setup this for Unit Test.

var result = data.ToList().Select(x=> this.mapper.Map<A_Class, B_Class>   (x)).ToList();

I am doign something like following

  this.mapperMock.Setup(x => x.Map<A_Class, B_Class>(AAA)).Returns(expectedResult);

Can anyone suggest what should be AAA and what should be expectedResult? In my controller my linq works foreach object of A_Class in Data. How can this be setup in UnitTest

1 Answers1

1

If you want to return your fake expectedResult no matter what value of A_Class is passed:

mapperMock.Setup(x => x.Map<A_Class, B_Class>(It.IsAny<A_Class>))
          .Returns(expectedResult);

If you want to be more specific, e.g. just return expectedResult for mapped A_Class with a property value of 'foo':

mapperMock.Setup(
         x => x.Map<A_Class, B_Class>(It.Is<A_Class>(_ => a.Property == "foo")))
    .Returns(expectedResult);

Note that if no setup matches, Moq will return a default value, which will be null for a reference type.

StuartLC
  • 104,537
  • 17
  • 209
  • 285
  • var result = data.ToList().Select(x=> this.mapper.Map (x)).ToList(); is return a List of B_Class. Should my expectedResult be a List or object of B_Class – InTheWorldOfCodingApplications Apr 10 '14 at 10:05
  • Just the one. The select will iterate your input list and will invoke `Map` to project a `B_Class` for each `A` which is then collated again in the `ToList` (you are mocking out just the `AutoMapper.Map`, not the whole of Linq :-) – StuartLC Apr 10 '14 at 10:07
  • Thanks a lot. Can you recommend me any good stuff on Unit Testing. I need to learn how to effectively test all layers e.g Repository, Service , MVC controllers etc. Some hands on tutorial or material – InTheWorldOfCodingApplications Apr 10 '14 at 10:13
  • How can i assert data.ShouldBeEquivalentTo(expectedResult); this ? – InTheWorldOfCodingApplications Apr 10 '14 at 10:31
  • If your method being tested is expected to return an exact instance, you can just check by reference, e.g. `Assert.AreEqual(expectedResult, actualResult)`. If not, you'll need to check each of the relevant properties on both, or alternatively, implement `IComparable` on the class of `expectedResult`, or even serialize both and compare the output. i.e. there is no magic method to compare all properties of 2 entities or a graph, AFAIK. One of the gurus in C# and Unit testing is Roy Osherove - a google should give you some good references / books. – StuartLC Apr 10 '14 at 10:39