我正在编写一个单元测试,我需要在其中模拟一个 JsObject,这样我就不需要在我的测试中进行实际的 javascript 互操作。但是,我使用索引运算符 []
来访问我的 JsObject 中的字段。我正在使用 dart mockito 库 https://github.com/fibulwinter/dart-mockito对于模拟,我似乎无法找到如何模拟运算符(operator)在模拟对象上的行为。
最佳答案
Mockito 使 stub 变得非常容易, stub 索引运算符的工作方式与 stub 任何其他方法一样。假设您想对以下类的索引运算符进行 stub :
class IndexTest {
operator[] (String value);
}
第一步,我们为该类创建一个模拟:
class MockIndexTest extends Mock implements IndexTest {
noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
现在在您的测试中,您可以使用索引运算符设置您期望的调用返回值:
test('Test', () {
final t = new MockIndexTest();
// Set return values
when(t[any]).thenReturn(0); // 1
when(t['one']).thenReturn(1); // 2
when(t['two']).thenReturn(2); // 3
// Check return values
expect(t['one'], equals(1));
expect(t['two'], equals(2));
expect(t['something else'], equals(0));
});
在没有 stub 的情况下,调用总是返回 null
。使用 mockito 提供的 any
值,您可以为带有任何参数的调用设置默认返回值(参见 1)。您还可以设置一组特定参数的返回值(参见 2 和 3)。在设置特定值之前,您必须先设置默认值。
关于unit-testing - 如何使用 dart mockito 模拟索引运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31166420/