如何使用 dart mockito 模拟索引运算符?
How can I mock the indexing operator with dart mockito?
我正在编写一个单元测试,我需要在其中模拟一个 JsObject,这样我就不需要在我的测试中进行实际的 javascript 互操作。但是,我正在使用索引运算符 []
来访问我的 JsObject 中的字段。我正在使用 dart mockito 库 https://github.com/fibulwinter/dart-mockito 进行模拟,但我似乎无法找到如何模拟操作员在模拟对象上的行为。
Mockito 使存根变得非常容易,存根索引运算符的工作方式与存根任何其他方法一样。想象一下你要对下面的class:
的index操作符进行stub
class IndexTest {
operator[] (String value);
}
在第一步中,我们为此创建一个模拟 class:
class MockIndexTest extends Mock implements IndexTest {
noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
现在在您的测试中,您可以使用索引运算符为调用设置您期望的 return 值:
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));
});
总是 return 秒 null
不打断电话。使用 mockito 提供的 any
值,您可以为带有任何参数的调用设置默认 return 值(参见 1)。您还可以为一组特定的参数设置 return 值(请参阅 2 和 3)。在设置特定值之前,您必须先设置默认值。
我正在编写一个单元测试,我需要在其中模拟一个 JsObject,这样我就不需要在我的测试中进行实际的 javascript 互操作。但是,我正在使用索引运算符 []
来访问我的 JsObject 中的字段。我正在使用 dart mockito 库 https://github.com/fibulwinter/dart-mockito 进行模拟,但我似乎无法找到如何模拟操作员在模拟对象上的行为。
Mockito 使存根变得非常容易,存根索引运算符的工作方式与存根任何其他方法一样。想象一下你要对下面的class:
的index操作符进行stubclass IndexTest {
operator[] (String value);
}
在第一步中,我们为此创建一个模拟 class:
class MockIndexTest extends Mock implements IndexTest {
noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
现在在您的测试中,您可以使用索引运算符为调用设置您期望的 return 值:
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));
});
总是 return 秒 null
不打断电话。使用 mockito 提供的 any
值,您可以为带有任何参数的调用设置默认 return 值(参见 1)。您还可以为一组特定的参数设置 return 值(请参阅 2 和 3)。在设置特定值之前,您必须先设置默认值。