How to assert if a method was called within another method in RhinoMocks?

ⅰ亾dé卋堺 提交于 2020-01-06 08:37:32

问题


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:


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.




回答2:


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)));


来源:https://stackoverflow.com/questions/2774875/how-to-assert-if-a-method-was-called-within-another-method-in-rhinomocks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!