Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. There's a class that has a property with validation in the set {} component. 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. 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!

like image 479
McMuttons Avatar asked Aug 26 '11 08:08

McMuttons


1 Answers

Adapted from the Moq docs

mock.SetupSet(foo => foo.Name = "foo").Throws<ArgumentException>();
like image 121
Siy Williams Avatar answered Oct 31 '22 09:10

Siy Williams