NSubstitute-模拟任何参数的参数行为 [英] NSubstitute - mock out parameter behaviour for any parameter

查看:152
本文介绍了NSubstitute-模拟任何参数的参数行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用NSubstitute模拟 IConfigurationProvider 。我需要方法 bool TryGet(string key,out string value)返回不同键的值。像这样:

I'm trying to mock IConfigurationProvider with NSubstitute. I need the method bool TryGet(string key, out string value) to return values for differing keys. So something like this:

var configProvider = Substitute.For<IConfigurationProvider>();
configProvider.TryGet("key1", out Arg.Any<string>()).Returns(x => 
    { x[1] = "42"; return true; });

,但这无法编译。
我需要一个模拟方法来实际将out参数设置为适当的值,而不管该参数是什么-它是一个依赖项,被测单元使用自己的参数调用此方法,而我只是希望它返回(例如,通过填写out参数作为回报)密钥的正确值。

but this does not compile. I need the mocked method to actually set the out parameter to the appropriate value, regardless of what that parameter is - it's a dependency, the unit under test calls this method with its own parameters and I just want it to "return" (as in return by filling the out parameter) correct values for keys.

这应该为问题提供更多视角:

This should give more perspective on the problem:

var value = "";
var configProvider = Substitute.For<IConfigurationProvider>();
configProvider
.TryGet("key1", out value)
.Returns(x => { 
    x[1] = "42"; 
    return true; 
});

var otherValue = "other";
configProvider.TryGet("key1", out value);
configProvider.TryGet("key1", out otherValue);

Assert.AreEqual("42", value);      // PASS.
Assert.AreEqual("42", otherValue); // FAIL.

我需要两个断言都是正确的,因为该方法将由被测试的类使用并且是免费的传递所需的任何out参数,我只需要用 42填充。

I need both assertions to be true, since this method will be used by the tested class and it's free to pass any out parameter it wants, I just need to fill it with "42".

推荐答案

configProvider.TryGet( key1,Arg.Any< string>())无效的C#语法,这就是为什么它不会编译的原因。

configProvider.TryGet("key1", out Arg.Any<string>()) is not valid C# syntax, which is why it wont compile.

您需要为 out 参数使用实际变量。

You need to use an actual variable for the out parameter.

经测试,以下工作有效。

The following works when tested.

//Arrange            
var expectedResult = true;
var expectedOut = "42";
var actualOut = "other";
var anyStringArg = Arg.Any<string>();
var key = "key1";
var configProvider = Substitute.For<IConfigurationProvider>();
configProvider
    .TryGet(key, out anyStringArg)
    .Returns(x => {
        x[1] = expectedOut;
        return expectedResult;
    });

//Act
var actualResult = configProvider.TryGet(key, out actualOut);

//Assert
Assert.AreEqual(expectedOut, actualOut); // PASS.
Assert.AreEqual(expectedResult, actualResult); // PASS.

这篇关于NSubstitute-模拟任何参数的参数行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆