views:

186

answers:

2

When writeing unit tests for a single class that contains other objects what's the best way to use

mock objects to avoid tests dependant on other classes.

Example 1:

public class MyClass
{
   protected MyObject _obj;

   public MyClass()
   {
       _obj = new MyObject();
   }

   public object DoSomething()
   {
      //some work
      _obj.MethodCall();
      //more work;
      return result;
   }
}

I'd rather not expose the protected value to create a unit test for the code. A wrapper class would

work for testing but is there a better way?

Example 2:

public class MyClass
{

   public object DoSomething()
   {

      //some work
      MyObject obj = new obj(parameters);
      _obj.MethodCall(Method1);
      //more work;
      return result;
   }

   public int Method1()
   { ... }    

}

Similar to the above example but the ojbect is created in the method I am calling.

Example 3:

public class MyClass
{

   public object DoSomething()
   {

      //some work
      obj.MethodCall(Method1);
      //more work;
      return result;
   }

   public int MethodA()
   { ... }    

}

Is there a way to test MethodA when it is only used as a delegate?

A: 

Have you tried deriving a UTMyClass from MyClass?

McWafflestix
+1  A: 

I recommend that you take a look at dependency injection. One thing is using mock objects, but unless you're using something like TypeMock, which basically lets you modify you code on the fly, you want to have a way to inject the instances your class depends on if you want to get rid of the dependencies. So in examples 1, I would suggest that instead of newing an instance of MyObject in the constructor, you could have the caller supply that instance. In that case you would easily by able to replace it with a mock or even a stub.

Brian Rasmussen