How can I mock the mockito dart indexing operator?
I am writing a unit test in which I need to mock a JsObject so that I don't have to do actual javascript interaction in my test. However, I am using the indexing operator []
to access the field in my JsObject. I am using the dart mockito library https://github.com/fibulwinter/dart-mockito for mocking, and I cannot find how I am fooling the behavior of the operators on the mocking object.
source to share
Mockito makes trimming very easy, with the stubbing index operator working just like wrapping any other method. When rendering, you want to stub the index operator of the following class:
class IndexTest {
operator[] (String value);
}
In the first step, we create a layout for this class:
class MockIndexTest extends Mock implements IndexTest {
noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
Now in your test, you can set the return values ββthat you expect for invocations using the index operator:
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));
});
Without interrupting the call, it always returns null
. With the value any
provided by mockito, you can set a default return value for calls with any argument (see 1). You can also set the return value for a specific set of parameters (see 2 and 3). Before setting certain parameters, you must set the default value.
source to share