chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
0 votes
I have to create a testscenario, where I have to simulate that a method throws an exception the first two calls and in the remaining calls the method follows it's own flow.

If I use the Mock.AlwaysThrow-method, an exception is thrown everytime the method is called. So how do I make the method throw an exception a certain amount of times ?
asked by lyd (600 points)

1 Answer

0 votes
Hi
You can do that like this in reflective mocks:

mock.ExpectAndThrow("MyMethod", new MyException(), 2);


The last parameter to ExpectAndThrow method is number of times to throw the exception.

And using natural mocks:
using (RecordExpectations recorder = RecorderManager.StartRecording())
{
    MyClass mock = new MyClass();
    recorder.ExpectAndThrow(mock.MyMethod(), new MyException()).Repeat(2);
}


Here you the Repeat method handles the number of time to throw the exception.
answered by ohad (35.4k points)
...