简体   繁体   English

我如何使用Moles为C#中的一个方法的多次调用返回不同的值?

[英]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. 在此方法中,存在一个我无法真正解决的外部依赖关系,因此我将不得不使用Moles来创建我的单元测试。

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. 这种外部依赖关系包含一个实例的方法,该方法被称为多次(两次),第二次我想使用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. 当我在上面的那一行后面写另一行并返回“ false”时,该行“覆盖”了第一行,因此,我总是会得到false。

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. 第一次调用将返回true,第二次返回false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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