Reputation: 12064
I've used Moq's linq to mocks feature before but only for setting properties or return values from simple functions. I'm curious whether there is a way to configure a mock object to throw an exception using Mock.Of<>
?
It accepts an Expression<Func<T, bool>>
as a predicate. If it is capable of using a linq expression to configure a mocked method to throw an exception, I'm drawing a blank on the correct syntax to do it.
Is this even possible?
Upvotes: 1
Views: 319
Reputation: 18013
From the Quickstart:
LINQ to Mocks is great for quickly stubbing out dependencies that typically don't need further verification. If you do need to verify later some invocation on those mocks, you can easily retrieve them with
Mock.Get(instance)
.
Though it does not mention exceptions explicitly the same applies to them as well:
var mockService = Mock.Of<ISomeService>(/*your usual declarative setup*/);
// adding exceptions by reverting to classic setup:
Mock.Get(mockService).Setup(s => s.MyMethod()).Throws(myException); // or Returns/Verify/etc.
So the best you can do is to mix the two ways. Simple setup can be done by the Mock.Of<>
and verification/exceptions can be added by retrieving the internally created mock by Mock.Get()
.
Upvotes: 3