NSubstitute - 使成员 return 成为 lambda 调用的结果

NSubstitute - Make member return result of a lambda invocation

我们都知道为替代指定 return 值的方式标准:

mySubstitute.Method().Returns(myValue);

不过,我需要在每次调用时计算 myValue,而不仅仅是一次。这可能吗?

示例:

mySubstitute.Method().Returns(() => ComputeValueBasedOnSystemClockAndTheWeather());

当然这不会编译,因为 Method() 并不是真正的 return lambda。

我跳转到 NSubstitue 文档,看到他们有一个页面 Return from a function

The return value for a call to a property or method can be set to the result of a function. This allows more complex logic to be put into the substitute. Although this is normally a bad practice, there are some situations in which it is useful.

calculator
    .Add(Arg.Any<int>(), Arg.Any<int>())
    .Returns(x => (int)x[0] + (int)x[1]);