views:

39

answers:

1

I have a class that has two methods. One method needs to call the other method and in my test I want to assert that it was called.

public class Tasks : ITasks
{
  public void MethodOne()
  {
    MethodTwo(1);
  }

  public int MethodTwo(int i)
  {
    return i + 1;
  }
}

I want to mock Tasks and do something like tasks.AssertWasCalled(x => x.MethodTwo(1)). Must MethodTwo be virtual?

+1  A: 

The concept you're looking for is partial mocks (this shows old syntax, but I don't remember the new one off the top of my head). You should read up on it. Essentially you create the mock on Tasks (not ITasks) and tell it to mock out only MethodTwo (which needs to be virtual).

However...you might want to reconsider your design. What is ITasks? What is the role? Are they different actual tasks? Is there any reason why you would want them in the same class? My understanding is that partial mocks is only included for when you need to test legacy components - I've never found a use for it.

George Mauer
That's just an example class for the purposes of simplifying the question. :) In the real code I have a tasks (application services) class that comes from SharpArchitecture. Anyway, I'm already starting to see bad design - that method should not be virtual if I'm not going to inherit from that class, following the example MethodTwo() is used only by MethodOne() which is a leftover from my previous thinking, I guess (I thought it would be used by another class), so it should probably be made private now and private methods are not mocked / tested... Thanks for the link to partial mocks. :)
Pawel Krakowiak