Posts

Showing posts with the label Moq

Moq'ing Successive Calls to a Method - void method exception handling

My last post expanded on a piece of code I found on Phil Haack's blog that extends Moq to allow you to return different values on each successive call to a method - I also improved it to allow you mock up any of the iterations to throw an exception in place of the return value. This is great for methods that actually return values, but what happens when you want to throw optional exceptions when you invoke void methods in Moq? Well, void methods on Moq mocks return ISetup<TMock> instead of ISetup<TMock, TResult>, which means that you can't use the ReturnsInOrder method to handle exceptions. Normally, you would just append a .Throws() to the respective Setup method, but Throws() has no params[] parameter, and no Action based override (as Returns() does), so the only way to apply this kind of rule is with recursive callbacks, which are both cumbersome and hard to read. This is demonstrated below; I'm mocking up a call to an FTP class. The first and third calls ...

Moq'ing Successive Calls to a Method

I just ran into a little problem when using Moq - I wanted to be able to mock up the result of a method call, but return a different result each time the mocked method was called (I'm pulling messages out of an MSMQ within a loop). Anyone who's used Moq will know that you usually mock results with the Setup() method - however, Moq has no built in way of achieving this (that I'm aware of). To cut a long explanation short, I found a series of articles on Phil Haack's blog addressing (almost) the same issue. Phil's second post adds exception handling to his original example, but I wanted to return a "null", rather than throw an exception. Here's the code from Phil's blog, slightly rehashed to deal with nulls: public static class MoqExtensions { public static IReturnsResult<T> ReturnsInOrder<T, TResult>( this ISetup<T, TResult> setup, params object [] results) where T: class { var que...