1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| when(cat.eatFood("fish")).thenReturn(true);
swhen(cat.walk(["roof","tree"])).thenReturn(2);
when(cat.eatFood(argThat(startsWith("dry")))).thenReturn(false); when(cat.eatFood(any)).thenReturn(false);
when(cat.eatFood(argThat(startsWith("dry")), hungry: true)).thenReturn(true); expect(cat.eatFood("fish"), isTrue); expect(cat.walk(["roof","tree"]), equals(2)); expect(cat.eatFood("dry food"), isFalse); expect(cat.eatFood("dry food", hungry: true), isTrue);
verify(cat.eatFood("fish")); verify(cat.walk(["roof","tree"]));
verify(cat.eatFood(argThat(contains("food"))));
cat.lives = 9; verify(cat.lives=9); 如果一个参数不是 ArgMatcher, (如 any、 anyNamed、 argThat、 captureThat、等) 传递给 mock 方法的参数,那么 equals 匹配器用于参数匹配。 如果需要更严格的匹配,考虑下使用 argThat(identical(arg))。 尽管这样,注意 null 不能用作 ArgMatcher 参数相邻的参数,或传递一个未包装的值作为命名参数。例如: verify(cat.hunt("backyard", null)); verify(cat.hunt(argThat(contains("yard")), null)); verify(cat.hunt(argThat(contains("yard")), argThat(isNull))); verify(cat.eatFood("Milk", hungry: null)); verify(cat.eatFood("Milk", hungry: argThat(isNull)));
### 命名参数
关于此语法,Mockito 现在有一个尴尬的麻烦:命名参数和参数匹配器需要比想象中更多的配置:必须在参数匹配器中声明参数的名称。这是因为我们无法依赖命名参数的位置,并且语言没有提供一个机制来回答 ”这个元素是在用作命名元素” 吗?
```dart
when(cat.eatFood(any, hungry: anyNamed('hungry'))).thenReturn(true); when(cat.eatFood(any, hungry: argThat(isNotNull, named: 'hungry'))).thenReturn(false); when(cat.eatFood(any, hungry: captureAnyNamed('hungry'))).thenReturn(false); when(cat.eatFood(any, hungry: captureThat(isNotNull, named: 'hungry'))).thenReturn(true);
when(cat.eatFood(any, hungry: any)).thenReturn(true); when(cat.eatFood(any, hungry: argThat(isNotNull))).thenReturn(false); when(cat.eatFood(any, hungry: captureAny)).thenReturn(false); when(cat.eatFood(any, hungry: captureThat(isNotNull))).thenReturn(true);
|