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

Isolator AAA: Setting Behavior

After we created fakes, now we can set specific behavior. As you may recall, the default behavior is set when the fake is created. Using the WhenCalled API, we can now set the behavior of a specific method.

Setting a method looks like this:

Note that the WhenCalled clauses are sort of a default behavior for the method. Read the last line as: “From now on, for every Increment method, ignore the call”. In the future we’ll be adding repeats and conditionals.

Things you can do with WhenCalled:

    • CallOriginal – Calls the original implementation.
    • WillThrow – Throws a specific exception
    • IgnoreCall – Ignores the real implementation (for void methods only).
    • WillReturn – Ignores the real implementation and returns a value (for non-void methods only)


Because of the type of the value returned (or void if not), you can only set appropriate behavior per this return type. If this is a void method, you cannot call WillReturn on it. And in the same manner, if it returns something, you can’t use IgnoreCall. This is prevented at compile time, which is very handy.

Use WhenCalled, along with the Fake creation smartly, and you can save yourself precious lines of code. Here’s an example:

Note that we’re using Members.CallOriginal for our fake, which sets the default behavior for calling all methods as-is. But for a single method, I’m setting IgnoreCall behavior. If you want a whole fake object and ancestry, and only one method should be return a set value, you can use this:

The final trick is to use chains. Behold this magnificent example:

The fake is recursive. Note that we set the behavior on a chain of calls. The entire chains returns 20. A regular DoSomething() doesn’t.

The same works for verifying calls, which is the subject off the next post.

Want to start unit testing? Take advantage of our 30-day FREE trial of Isolator Complete. Get it now