How to assert if a method was called within anothe

2019-09-02 04:47发布

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?

2条回答
啃猪蹄的小仙女
2楼-- · 2019-09-02 05:04

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.

查看更多
何必那么认真
3楼-- · 2019-09-02 05:10

Of course my thinking at that time was flawed. I should be mocking ITasks, not the implementation (Tasks):

ITasks tasks = MockRepository.GenerateMock<ITasks>();
tasks.AssertWasCalled(x => x.MethodTwo(Arg<int>.Is.Equal(1)));
查看更多
登录 后发表回答