2

I'm doing lots of unit tests lately and I've discovered the Mock.Of<T> method from Moq library. After reading this and ultimately that I've found out that Mock.Of is great option for creating mocked interface instance, but what about regular classes which I can make object myself by new keyword? Some Nunit tutorials uses that approach and it's confusing for me because I don't find it useful in any way.

    Person newPerson = new Person() { Name = "David", Surname = "Smith" };
    Person mockedPerson = Mock.Of<Person>(o => o.Name == "David" && o.Surname == "Smith");

Is there any difference between those two objects? In this case Mock.Of have any advantage or should I use regular new keyword to create new instance of class?

erexo
  • 503
  • 1
  • 6
  • 24

1 Answers1

4

I think the code you showed misses the point of mocking completely. Mocking is supposed to work on interfaces and abstract classes so you don't have to create actual objects. Either that or you create a mock of an object

So, you can do Mock.Of<Person> and then you assign some values needed in your tests, but what you do not do is create the object first and set it up and then create a mock of it.

Assume you have code like this :

public interface IPerson
{
     some method and property signatures
}

then you have

public class Person : IPerson
{ 
    some code here
}

now imagine you have a method which takes IPerson as parameter

then you can do something like:

var mockedPerson = Mock.Of<IPerson>();
mockedPerson.Age = 27;

int age = GetAge(mockedPerson);
Assert.AreEqual(age, 27)

creating a mock of an actual object makes no sense to me.

Andrei Dragotoniu
  • 6,155
  • 3
  • 18
  • 32
  • Yes I totally agree with you. Thats why I get so confused when I saw this approach in some tutorials, and also that's why I've came here with this question. Sadly I've lost sources so I'm unable to point to those tutorials – erexo Sep 26 '17 at 07:44