Usage of Moq When(Func<bool>) method

廉价感情. 提交于 2019-12-21 03:13:26

问题


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.


回答1:


"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);



回答2:


With this method you can configure your mocked object's behavior when the condition set in Mock<T>.When(...) evaluates to true. This enables your mocked object to react differently depending on the given condition.



来源:https://stackoverflow.com/questions/7767253/usage-of-moq-whenfuncbool-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!