【问题标题】:How to Mock a Delegate Action Input Parameter如何模拟委托操作输入参数
【发布时间】:2012-08-07 14:47:59
【问题描述】:

我正在尝试在下面的(配对)单元测试示例中安排传递给ICallback#Regsiter<T>(Action<T>) 的 lambda 输入参数(请参阅单元测试示例中的 cmets)。我试图避免必须抽象出 lambda,因为它是如此具体和小,但我不确定这是否可能。

// IBus interface peek
public interface IBus {
    ICallback Send(IMessage message);
}

// ICallback interface peek
public interface ICallback {
    void Register<T>(Action<T> callback);
}

public enum ReturnCode { Success }

// Controller
public class FooController : AsyncController {
    readonly IBus _bus;
    //...
    // Action being unit tested
    public void BarAsync() {
        _bus
            .Send(ZapMessageFactory.Create())
            .Register<ReturnCode>(x => {
                AsyncManger.Parameters["returnCode"] = x;
            });
    }

    public ActionResult BarCompleted(ReturnCode returnCode) {
        // ...
    }
}

// Controller action unit test
[TestClass]
public class FooControllerTest {
    [TestMethod}
    public void BarTestCanSetAsyncManagerParameterErrorCodeToSuccess() {
        var fooController = ControllerUTFactory.CreateFooController();
        // HOW DO I MOCK THE ACTION DELEGATE PARAMETER TO BE ReturnCode.Success
        // SO I CAN DO THE ASSERT BELOW???
        fooController.BarAsync();
        Assert.AreEqual(ReturnCode.Success, (ReturnCode)fooController.AsyncManager.Parameters["returnCode"]);
    }
}

【问题讨论】:

    标签: asp.net-mvc-3 unit-testing lambda moq anonymous-function


    【解决方案1】:

    使用Mock&lt;T&gt;#Callback() 就是答案:

    [TestMethod}
    public void BarTestCanSetAsyncManagerParameterErrorCodeToSuccess() {
        var mockCallback = new Mock<ICallback>();
        mockCallback
                .Setup(x => x.Register(It.IsAny<ReasonCode>())
                // THIS LINE IS THE ANSWER
                .Callback(action => action(ReasonCode.Success));
        var mockBus = new Mock<IBus>();
        mockBus
                .Setup(x => x.Send(It.IsAny<ZapMessage>())
                .Returns(mockCallback.Object);
    
        var fooController = new FooController(mockBus.Object);
    
        fooController.BarAsync();
        Assert.AreEqual(ReturnCode.Success, (ReturnCode)fooController.AsyncManager.Parameters["returnCode"]);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-19
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多