How to make a false exception throw the first time and return the second value

I use Moq as my mocking structure, and I need to test a class that, when a certain type of exception is thrown, will continue trying until the situation is resolved as soon as this happens. Execution ends.

So I need something similar to:

myMock = Mock<IFoo>(); myMock.Setup(m => m.Excecute()).Throws<SpecificException>(); myMock.Setup(m => m.Execute()); var classUnderTest = MyClass(myMock); classUnderTest.DoSomething(); Assert.AreEqual(expected, classUnderTest.Result); 

Thanks for any help you can give.

+7
source share
2 answers

This is one way, based on the Moq QuickStart example, to return different values ​​for each call.

 var mock = new Mock<IFoo>(); var calls = 0; mock.Setup(foo => foo.GetCountThing()) .Returns(() => calls) .Callback(() => { calls++; if (calls == 1) { throw new InvalidOperationException("foo"); } }); try { Console.WriteLine(mock.Object.GetCountThing()); } catch (InvalidOperationException) { Console.WriteLine("Got exception"); } Console.WriteLine(mock.Object.GetCountThing()); 

If the method returns void, use:

 var myMock = new Mock<IFoo>(); bool firstTimeExecuteCalled = true; myMock.Setup(m => m.Execute()) .Callback(() => { if (firstTimeExecuteCalled) { firstTimeExecuteCalled = false; throw new SpecificException(); } }); try { myMock.Object.Execute(); } catch (SpecificException) { // Would really want to call Assert.Throws instead of try..catch. Console.WriteLine("Got exception"); } myMock.Object.Execute(); Console.WriteLine("OK!"); 
+15
source

Why not write your own test object that does this? If it will just be used for testing, for example, something like:

 public class Mock : IFoo { private int _calls; public Mock() { _calls = 0; } public int Execute() { _calls++; if (_calls == 1) throw new Exception(); return value; } } 
+1
source

All Articles