编程语言
首页 > 编程语言> > c#-检查使用Rhino.Mocks传递给委托的期望值

c#-检查使用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?被嘲笑的服务不在我的控制之下,因此我无法更改其签名.

解决方法:

以下模式将允许您断言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"
    //

}

标签:unit-testing,assert,c,lambda,rhino-mocks
来源: https://codeday.me/bug/20191026/1939003.html