简体   繁体   中英

How can I use Moles to return different values for multiple calls to a method in C#?

I've been trying to find a solution for this, but either I've been looking with the wrong search terms or there simply isn't an answer for my question yet.

Problem: I've got a method that I'd like to write a unit test for. Within this method there is an external dependency that I can't really resolve, so I'll have to use Moles to create my unit test.

This external dependency consists of a method on an instance that is called multiple (two) times, and the second time I'd like to return a different value with Moles.

...
bool myVar = SomeInstance.SomeMethod(); // Here I'd like to return true
if( myVar )
...
...
bool myOtherVar = SomeInstance.SomeMethod(); // Here I'd like to return false
...

Now usually I set it up like

MSomeInstance.SomeMethod.AllInstances.SomeMethod = @this => true;

But how can I have different behaviours for both calls? When I write another line following the one above with "false" being returned, this "overwrites" the first one, so I'll always get false as a result.

Any ideas?

It's a bit ugly, but possible:

var toggle = false;
MSomeInstance.SomeMethod.AllInstances.SomeMethod =
    @this => { toggle = !toggle; return toggle; };

The first call will return true, the second false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM