c# - NSubstitute:如何访问返回中的实际参数

标签 c# unit-testing mocking nsubstitute

我想访问 NSubstitute 中的实际参数 Returns方法。例如:

var myThing = Substitute.For<IMyThing>()
myThing.MyMethod(Arg.Any<int>).Returns(<actual parameter value> + 1)

使用 NSubstitute 我应该写什么来代替 <actual parameter value> ,或者我怎样才能实现等效的行为?

最佳答案

根据 Call information documentation

The return value for a call to a property or method can be set to the result of a function.

var myThing = Substitute.For<IMyThing>()
myThing
    .MyMethod(Arg.Any<int>())
    .Returns(args => ((int)args[0]) + 1); //<-- Note access to pass arguments

lambda 函数的参数将允许访问在指定的从零开始的位置传递给此调用的参数。

对于强类型参数,还可以执行以下操作。

var myThing = Substitute.For<IMyThing>()
myThing
    .MyMethod(Arg.Any<int>())
    .Returns(args => args.ArgAt<int>(0) + 1); //<-- Note access to pass arguments

T ArgAt<T>(int position): Gets the argument passed to this call at the specified zero-based position, converted to type T.

由于在这种情况下只有一个参数,因此可以进一步简化为

var myThing = Substitute.For<IMyThing>()
myThing
    .MyMethod(Arg.Any<int>())
    .Returns(args => args.Arg<int>() + 1); //<-- Note access to pass arguments

在这里args.Arg<int>()将返回 int传递给调用的参数,而不必使用 (int)args[0] .如果有多个,则将使用索引。

关于c# - NSubstitute:如何访问返回中的实际参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44845253/

相关文章:

c - C 中单元测试的自动生成器

angularjs - AngularJS HTTP 中的模拟服务

c# - 删除制表符空格?

c# - 类数组

c# - 如何覆盖 WPF C# 中的内置事件处理程序

python - "Zero Iteration"- 简单联系表功能中的端到端验收测试

python - 如何使用 Python 的单元测试断言数据库错误?

java - 如何更改 Mockito 中字符串的默认返回值?

python - 在 python 中测试时如何删除装饰器的效果?

c# - 使用 C# 双缓冲有负面影响