Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq: Setup a mocked method to fail on the first call, succeed on the second

What's the most succinct way to use Moq to mock a method that will throw an exception the first time it is called, then succeed the second time it is called?

like image 956
anthony Avatar asked Aug 12 '11 19:08

anthony


People also ask

What can be mocked with Moq?

Unit testing is a powerful way to ensure that your code works as intended. It's a great way to combat the common “works on my machine” problem. Using Moq, you can mock out dependencies and make sure that you are testing the code in isolation. Moq is a mock object framework for .

How does Moq mock work?

Mock objects allow you to mimic the behavior of classes and interfaces, letting the code in the test interact with them as if they were real. This isolates the code you're testing, ensuring that it works on its own and that no other code will make the tests fail.

What does Moq callback do?

A powerful capability of Moq is to attach custom code to configured methods and properties' getters and setters. This capability is often referred to as Callbacks.


2 Answers

I would make use of Callback and increment a counter to determine whether or not to throw an exception from Callback.

[Test] public void TestMe() {     var count = 0;     var mock = new Mock<IMyClass>();     mock.Setup(a => a.MyMethod()).Callback(() =>         {             count++;             if(count == 1)                 throw new ApplicationException();         });     Assert.Throws(typeof(ApplicationException), () => mock.Object.MyMethod());     Assert.DoesNotThrow(() => mock.Object.MyMethod()); }  public interface IMyClass {     void MyMethod(); } 
like image 67
rsbarro Avatar answered Sep 20 '22 21:09

rsbarro


Starting with Moq 4.2 you can just use the built-in method SetupSequence() (as stated by @RichardBarnett comment).

Example:

var mock = new Mock<IMyClass>(); mock.SetupSequence(x => x.MyMethod("param1"))     .Throws<MyException>()     .Returns("test return"); 
like image 39
aghidini Avatar answered Sep 20 '22 21:09

aghidini