简体   繁体   中英

Constructing mocks in unit tests

Is there any way to have a mock constructed instead of a real instance when testing code that calls a constructor?

For example:

public class ClassToTest
{
  public void MethodToTest()
  {
    MyObject foo = new MyObject();
    Console.WriteLine(foo.ToString());
  }
}

In this example, I need to create a unit test that confirms that calling MethodToTest on an instance of ClassToTest will indeed output whatever the result of the ToString() method of a newly created instance of MyObject.

I can't see a way of realistically testing the 'ClassToTest' class in isolation; testing this method would actually test the 'myObject.ToString()' method as well as the MethodToTest method.

Not really. Your ClassToTest is hard to test because of its design. If you want to be able to swap out its dependencies for mock objects, then you need to think about how these dependencies are injected - but just creating them in the constructor is not an approach that is going to help you. You could use constructor injection:

public class ClassToTest
{
  MyObject _foo;
  public void MethodToTest(Myobject foo)
  {
    _foo = foo;
    Console.WriteLine(foo.ToString());
  }
}

or you could use property injection:

public class ClassToTest
{
  public MyObject Foo { get; set; }
  public void MethodToTest()
  {
  }
}

The former may suit your example more given you want to write out the console there; it is often the best approach when your dependency is a must have dependency for the object rather than an optional one.

You could do a lot worse than exploring the concepts of dependency injection and inversion of control .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM