如何仅使用Sinon模拟一种方法?

丹尼尔·卡普兰

我在我的命名空间中只有一个方法要模拟,但我希望其他所有方法都能正常工作。是否可以让sinon模拟一种特定的方法,而使其他方法保持不变?

我的理解是我不是在寻找间谍,因为我想断言该模拟是使用特定参数调用的。

这是我在CoffeeScript中的代码:

root.targeting.handleUnitsAttack = (gameState) ->
  units = gameState.heroes.concat(gameState.badGuys)
  for source in units
    for target in units
      gameState = root.targeting.sourceAttackTarget(gameState, source, target)
  gameState

我想模拟sourceAttackTarget并验证其参数是否为特定值。

布吉兹

是的,那是sinon @ 2最常见的用例之一,但是我相信您所寻找的不是模拟也不是间谍,而是存根。

参见:https : //sinonjs.org/releases/v2.4.1/stubs/

var stub = sinon.stub(object, "foo");
//do your assertions
stub.restore(); //back to normal now.

这将允许您创建一个默认函数替换object.foo()

但是,从您的问题来看,这听起来像是您不希望使用的无操作存根函数,而是想用自己的自定义函数覆盖它:

var stub = sinon.stub(object, "foo", function customFoo() { /* ... */ });
//do your assertions
stub.restore(); //back to normal now.

HTH!


编辑:

如何对单个函数进行存根:

以下存根 object.sourceAttackTarget()

var stub = sinon.stub(object, "sourceAttackTarget", function sourceAttackTargetCustom(gameState, source, target) {
    //do assertions on gameState, source, and target
    // ...
    return customReturn;
});
//do any further assertions
stub.restore(); //back to normal now.

如何存根函数以测试特定参数

var stub = sinon.stub(object, "sourceAttackTarget");
stub.withArgs(1, "foo", "bar").returns("correctTarget");
stub.returns("wrongTarget");
var output = object.sourceAttackTarget(gameState, source, target);
equal(output, "correctTarget", 'sourceAttackTarget invoked with the right arguments');
//do any further assertions
stub.restore(); //back to normal now.

(更新)

也有.calledWith().calledWithMatch(),我只是发现了约。对于这类测试,也可能非常有用。

如何仅模拟对象的一种方法:

“模拟程序带有内置的期望,它们可能无法通过测试。因此,它们会强制执行实现细节。经验法则是:如果您不为某个特定的调用添加断言,请不要模拟它。使用存根代替通常,在一个测试中,您不应有一个以上的模拟(可能会有多个期望)。” -来源

...因此,对于上述问题,模拟不是正确的选择,而存根是适当的选择。话虽这么说,但是可以通过模拟轻松地测试其中一种情况,这是期望已使用一组特定的参数调用了一种方法。

var mock = sinon.mock(object);
mock.expects("sourceAttackTarget").withArgs(1, "foo", "bar");
object.sourceAttackTarget(gameState, source, target);
mock.verify();

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何仅模拟接口的一种方法

仅模拟Angular服务的一种方法

Mockito-仅模拟一种方法

如何模拟接口的一种方法?

如何使用PhpUnit模拟Laravel中的一种方法

如何仅模拟一种静态方法并测试另一种静态方法

如何仅使用一种方法来填充ComBobox和ListBox的项目?

如何仅使用一种方法制作此计算器?

有一种方法可以仅使用一种方法对FXML文件对象做出不同的响应?

如何使用一种方法注销任何守卫?

如何从另一种方法使用数组?

我如何将一种方法与另一种方法组合使用

如何在另一种方法中使用一种方法的“返回”值

如何多次模拟具有不同参数的一种方法?

如何编写UT以一种方法模拟内部对象?

phpunit仅在测试类中模拟一种方法-使用Mockery

从方法中仅调用一种方法

AngularJs中是否有一种方法可以使用Services以及仅模拟\ stub之类的$ http测试控制器?

在只读字段和仅使用getter的属性之间使用一种方法比使用另一种方法有什么好处?

仅将外部字段用于一种方法

C ++可能仅使一种方法模板化?

如何仅通过 JMS/Serializer 为一种方法公开属性?

Angularjs:如何使ui-select仅具有一种方法模型出价?

如何从另一种方法正确调用一种方法

仅使用一种方法更改不同的按钮文本

防止在另一种方法中使用一种方法

使用 List 从一种方法到另一种方法

使用一种方法的结果以另一种方法计算价格

如何使用其中一种方法返回同一接口的对象的接口?