1

我正在尝试ICallback#Regsiter<T>(Action<T>)在下面的(成对的)单元测试示例中安排传递给的 lambda 的输入参数(请参阅单元测试示例中的注释)。我试图避免必须抽象出 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"]);
    }
}
4

1 回答 1

0

使用Mock<T>#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"]);
}
于 2012-08-08T12:30:42.763 回答