Rhino Mocks - 使用Expect.Call获取具有两个签名的方法

时间:2012-03-13 20:50:56

标签: c# mocking nunit rhino-mocks

如何使用两个签名模拟方法?

sudo代码:

public Class ClassA{
  //... do stuff
}

public Class ClassB{
  //... do stuff
}

public Class BigClass
{
  public BigClass(){}

  public ClassB MapMe(ClassA a)
  {
     //... do stuff
     return new ClassB();
  }

  public ClassA MapMe(ClassB a)  
  {
     //... do stuff    
     return new ClassA();
  }
}

public Class ClassToTest
{
  public void DoSomething()
  {
     var ResultA = BigClass.MapMe(new ClassA());

     //... do some more stuff

     ResultA = BigClass.MapMe(new ClassB());
  }
}

为糟糕的代码示例道歉,在IPad上执行此操作,但希望能为您提供这个想法。

1 个答案:

答案 0 :(得分:7)

只需使用Argument Constraints

即可
  

参数约束还通过指定来定义方法的签名   参数类型。这就是为什么他们不能被省略。

mock.Expect(x => x.MapMe(Arg<ClassB>.Is.Anything).Return(resultB);
mock.Expect(x => x.MapMe(Arg<ClassA>.Is.Anything).Return(resultA);

编辑:

我相信你遇到的另一个问题 - 你在没有支持界面的情况下嘲笑BigClass,所以很明显RhinoMocks不允许对这样的模拟设置期望。所以只需通过接口抽象BigClass并基于它进行模拟:

public interface IMapper
{
    ClassB MapMe(ClassA entity);
    ClassA MapMe(ClassB entity);
}

public class BigClass : IMapper


[Test]
public void MapperTest()
{
    // !!! Below I've used WhenCalled() to show you that correct  
    // expectation is called based on argument type, just see in debugger
    IMapper mapperMock = MockRepository.GenerateMock<IMapper>();
    mapperMock.Expect(x => x.MapMe(Arg<ClassA>.Is.Anything))
              .WhenCalled((mi) =>
                        {
                            Debug.WriteLine("MapMe - ClassA parameter");
                        })
              .Return(null /*TODO: return correct instance*/);
    mapperMock.Expect(x => x.MapMe(Arg<ClassB>.Is.Anything))
              .WhenCalled((mi) =>
                        {
                            Debug.WriteLine("MapMe - ClassB parameter");
                        })
              .Return(null /*TODO: return correct instance*/);

    var resultB = mapperMock.MapMe(new ClassA());
    var resultA = mapperMock.MapMe(new ClassB());

   // TODO: Asserts
}