Moq When(Func< bool>)方法的用法 [英] Usage of Moq When(Func<bool>) method

查看:61
本文介绍了Moq When(Func< bool>)方法的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到Moq中when方法用法的示例

I can't find an example of the usage of the When method in Moq

When(Func<bool> condition);

该方法的目的/用途是什么?请提供一个代码示例,演示一个有用的方案.

What is the purpose/usage of the method? Please give a code sample demonstrating a scenario where it would be useful.

推荐答案

何时"使您可以选择对同一模拟对象进行不同的设置,具体取决于您要决定的内容.假设您要测试已编写的格式提供程序.如果程序(=测试)在早上运行,则某个函数调用应返回null;否则,返回null.下午有一定的价值.然后,您可以使用何时"编写这些条件设置.

"When" gives you the option to have different setups for the same mocked object, depending on whatever you have to decide. Let's say you want to test a format provider you have written. If the program (= test) runs in the morning a certain function call should return null; in the afternoon a certain value. Then you can use "When" to write those conditional setups.

var mockedService = new Mock<IFormatProvider>();

mockedService.When(() => DateTime.Now.Hour < 12).Setup(x => x.GetFormat(typeof(string))).Returns(null);
mockedService.When(() => DateTime.Now.Hour >= 12).Setup(x => x.GetFormat(typeof(string))).Returns(42);

这篇关于Moq When(Func&lt; bool&gt;)方法的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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