【问题标题】:How can I mock the indexing operator with dart mockito?如何使用 dart mockito 模拟索引运算符?
【发布时间】:2015-09-18 21:52:30
【问题描述】:
【问题讨论】:
标签:
unit-testing
dart
operators
mockito
【解决方案1】:
Mockito 使存根变得非常容易,对索引运算符进行存根就像对任何其他方法进行存根一样。想象你想要存根以下类的索引运算符:
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));
});
不存根调用总是返回null。使用 mockito 提供的 any 值,您可以为带有任何参数的调用设置默认返回值(参见 1)。您还可以为一组特定的参数设置返回值(参见 2 和 3)。您必须在设置特定值之前设置默认值。