模拟匿名回调

Mocking an anonymous callback

我有这样的方法:

    public class Args
    {
        public string Command {get;set;}
        public Action<string> LogHandler {get;set;}
    }

    public class MyClass
    {
        IRunner mRunner;

        public MyClass(IRunner runner)
        {
            mRunner = runner;
        }

        public string GetVersionText()
        {
            List<string> log = new List<string>();
            Args args = new Args()
            {
                Command = "getversion",
                LogHandler = (msg) => { log.Add(msg); }
            };
            mRunner.Execute(args);
            return log.FirstOrDefault(x => x.Contains("Version"));
        }
    }

我想测试接收到的不同输出,如何模拟 IRunner.Execute 方法,以便我可以控制它对 Args class 的 Action 属性 执行的操作?

您无法真正模拟回调,因为它是在被测对象中创建的。

我建议您在 Callback 中捕获 args 并调用

args.LogHandler(your_msg_here) 

在其中(回调)

假设 IRunner 是一个注入的依赖项,基于上面提供的示例的简单测试可能如下所示

// Arrange
string expected = "Message containing Version";
var runner = new Mock<IRunner>();
runner
    .Setup(_ => _.Execute(It.IsAny<Args>()))
    .Callback((Args args) => args.LogHandler(expected)); //<-- this will invoke the action

MyClass subject = new MyClass(runner.Object);

// Act
string actual = subject.GetVersionText();

//Assert - using Fluent Assertions
actual.Should().Be(expected);