简体   繁体   English

如何使用Moq模拟使属性在set上抛出异常?

[英]How do I make a property throw an exception on set with a Moq mock?

I'm working on getting some legacy code under test, and we're using Moq 4 for our isolation. 我正在努力获得一些遗留代码,我们正在使用Moq 4进行隔离。 There's a class that has a property with validation in the set {} component. 有一个类在set {}组件中有一个带有验证的属性。 I need it to throw an exception when called for one of my tests, but I can't get it to do it. 我需要它在调用我的一个测试时抛出一个异常,但我无法做到这一点。 I've tried the following: 我尝试过以下方法:

fakeNetwork
  .Setup(n => n.IpAddress)
  .Throws(new SystemNotFoundException("1.1.1.1");

No exception is thrown. 没有异常被抛出。

fakeNetwork
  .SetupSet(n => n.IpAddress)
  .Throws(new SystemNotFoundException("1.1.1.1");

This usage is obsolete. 这种用法已经过时了。 The replacement is .SetupSet(Action), but I'm not sure how I'd make an action that throws an exception. 替换是.SetupSet(Action),但我不确定如何进行抛出异常的操作。 We treat warnings as errors, so I don't know if this would work anyway, but since I won't be able to use the obsolete version anyway, I have't tried to turn the check off. 我们将警告视为错误,因此我不知道这是否会起作用,但由于无论如何我都无法使用过时的版本,所以我没有尝试过关闭检查。

Any tips would be very helpful! 任何提示都会非常有用!

改编自Moq文档

mock.SetupSet(foo => foo.Name = "foo").Throws<ArgumentException>();

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

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