使用Rhino.Mocks

时间:2016-08-18 22:13:14

标签: c# unit-testing lambda assert rhino-mocks

我正在尝试编写一个测试用例,该测试用例将确认传递给测试方法的参数值是否用于调用委托函数,该函数作为参数传递给模拟服务上的方法。下面的例子说明了我在做什么:

测试方法:

public IList<IResultData> GetResultData(int id)
{
    Func<IExternalInterface, List<ExternalData> getDataMethod = client => client.GetExternalData(id);     
    List<ExternalData> externalDataList = serviceClient.ExecuteService(getDataMethod, "GetExternalData"); 

    var result = new List<ResultData>();

    //Some code to convert externalDataList into an IList<IResultData>

    return result;
}

测试方法:

[TestMethod]
public void TestMethodCall()
{
    var mockServiceClient = MockRepository.GenerateMock<IServiceClient>();
    mockServiceClient.Expect(x => x.ExecuteService(
            Arg<Func<IExternalInterface, List<ExternalData>>.Is.NotNull,
            Arg<string>.Is.Equal("GetExternalData")));

    var myClass = new MyClass(mockServiceClient);

    var result = myClass.GetResultData(3);

    //Some assertions that result is as expected.
}

有没有办法断言传递给Execute方法的函数是从测试方法调用GetResultData()传递的id为3?被嘲笑的服务是在我不能控制的库中,因此我无法更改它的签名。

1 个答案:

答案 0 :(得分:4)

以下模式将允许您断言lambda:

[TestMethod]
public void TestMethod1()
{
    var wasCalled = false;

    var fakeService = MockRepository.GenerateStub<IExternalInterface>();

    fakeService.Stub(x => x.GetExternalData(1))
               .Return(new List<ExternalData>() {new ExternalData() {Id = 1}});

    fakeService.Stub(service => service.ExecuteService(Arg<Func<IExternalInterface, 
                     List<ExternalData>>>.Is.Anything, Arg<string>.Is.Anything))
               .WhenCalled(invocation =>
               {
                   wasCalled = true;
                   var func = (Func<IExternalInterface, List<ExternalData>>) invocation.Arguments[0];
                   var res = func(fakeService);

                   //
                   // Assert here the "res"
                   //


               }).Return(null);

    var target = new MyClass(fakeService);

    target.GetResultData(1);

    Assert. IsTrue(wasCalled);
}

但是,根据您提供的更好解决方案的代码,您可以使用Do方法,如下所示:

[TestMethod]
public void TestMethod1()
{
    var fakeService = MockRepository.GenerateStub<IExternalInterface>();

    fakeService.Stub(x => x.GetExternalData(1)).Return(new List<ExternalData>() {new ExternalData() {Id = 1}});

    fakeService.Stub(service => service.ExecuteService(Arg<Func<IExternalInterface, 
                                                       List<ExternalData>>>.Is.Anything, Arg<string>.Is.Anything))
               .Do(new Func<Func<IExternalInterface, List<ExternalData>>, string, List<ExternalData>>((func, str)=>func(fakeService)));

    var target = new MyClass(fakeService);

    var result = target.GetResultData(1);

    //
    // Assert here the "result"
    //

}