简体   繁体   English

通用方法的最小起订量设置不返回指定值

[英]Moq setup of generic method does not return specified value

I have a settings class where I have an interface with the following generic method: 我有一个设置类,其中有一个使用以下通用方法的接口:

T GetValue<T>(string key, bool optional = false, T defaultValue = default(T));

I am now working on another part that uses this setting system and is using the above method to extract information from the setting object: 我现在正在使用该设置系统的另一部分上,并且正在使用上述方法从设置对象中提取信息:

Machine.BaudRate = Settings.GetValue<int>("BAUDRATE");
Machine.ComPort = Settings.GetValue<int>("COMPORT");

I would like this to be tested by a unit test so I write the following: 我希望通过单元测试对它进行测试,因此我编写了以下内容:

Settings.Setup(s => s.GetValue<int>("BAUDRATE",It.IsAny<bool>(),It.IsAny<int>())).Returns(57600);
Settings.Setup(s => s.GetValue("COMPORT", It.IsAny<bool>(),It.IsAny<int>())).Returns(5);

But when I run the test it returns 0 on both of them. 但是,当我运行测试时,它们两个都返回0。 If I put in a callback I can see that callback is hit, so the setup has worked correctly. 如果我输入了回调,则可以看到该回调已被执行,因此安装程序已正确运行。 Why won't it return the values indicated in the setup? 为什么不返回设置中指示的值?

Callback example (I have a exception variable I just set to null to have something to break on during debug): 回调示例(我有一个异常变量,我只是将其设置为null,以便在调试期间中断某些操作):

Settings.Setup(s => s.GetValue("COMPORT", false,It.IsAny<int>())).Callback(() => ex = null).Returns(5);

I don't know why in my code I get 0 returned, but I found a way to verify my inputs. 我不知道为什么在我的代码中返回0,但是我找到了一种验证输入的方法。 My inputs are routed through the class i am testing and out to another interface. 我的输入将通过我正在测试的课程进行路由,然后输出到另一个接口。 Becuase of this I can just change setups on that facade to validate the input: 因此,我可以只更改该外观上的设置以验证输入:

Facade.SetupSet(f => f.BaudRate = It.IsAny<int>()).Callback((int value) => Assert.AreEqual(57600, value)).Verifiable();
Facade.SetupSet(f => f.ComPort = It.IsAny<int>()).Callback((int value) => Assert.AreEqual(5, value)).Verifiable();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM