我想测试当按钮被点击10次时,是否会按下路由。当被测试的小部件调用Modular.to.pushNamed()
方法时,会抛出以下错误
The following _TypeError was thrown running a test:
type 'Null' is not a subtype of type 'Future<Object?>'
When the exception was thrown, this was the stack:
#0 ModularNavigateMock.pushNamed (package:flutter_modular/src/presenter/models/modular_navigator.dart:40:14)
#1 AgileSmellsState.goToResults (package:serious_agile_games/agile-smells/agile_smells.dart:37:16)
#2 AgileSmellsState.build.<anonymous closure> (package:serious_agile_games/agile-smells/agile_smells.dart:50:26)
#3 SwipingDeck.swipeRight (package:swiping_card_deck/swiping_card_deck.dart:119:38)
<asynchronous suspension>
在AgileAmells
小部件中抛出异常的调用是
void goToResults() {
Modular.to.pushNamed(AgileSmellsResults.route, arguments: validatedSmells);
}
其中validatedSmells
是不可空的List.empty(growable: true)
我的测试是
testWidgets('Test validate smell 10 times', (tester) async {
await tester.pumpWidget(TestModularApp(widgetToTest: AgileSmells(firestore: firestore)));
await tester.pumpAndSettle();
final deck = find.byType(SwipingDeck<SmellCard>);
final validateButton = find.byIcon(Icons.check);
expect(deck, findsOneWidget);
expect(validateButton, findsOneWidget);
await tester.tap(validateButton);
await tester.pumpAndSettle();
verifyNever(
() => TestModularNavigation.mockedNavigator.pushNamed(AgileSmellsResults.route, arguments: any, forRoot: false),
);
for (int i = 1; i < 10; i++) {
await tester.tap(validateButton);
await tester.pumpAndSettle();
}
// Verify causing failure in the test
verify(
() => TestModularNavigation.mockedNavigator.pushNamed(AgileSmellsResults.route, arguments: any, forRoot: false),
).called(1);
});
我模拟的ModularNavigate类
class ModularNavigateMock extends Mock implements IModularNavigator {}
class TestModularNavigation {
static final mockedNavigator = ModularNavigateMock();
static void setUp() {
Modular.navigatorDelegate = mockedNavigator;
when(() => mockedNavigator.pushNamed(AgileSmellsResults.route, arguments: any)).thenAnswer((_) async => const AgileSmellsResults());
}
}
谢谢你的帮助
通过阅读pub.dev上的Mocktail FAQ和文档解决
问题是pushNamed
方法的错误存根。我将arguments: any
更改为arguments: any(named: 'arguments')
,以便在mockedNavigator
和verify
步骤中正确存根
我的固定mockedNavigator
class ModularNavigateMock extends Mock implements IModularNavigator {}
class TestModularNavigation {
static final mockedNavigator = ModularNavigateMock();
static void setUp() {
Modular.navigatorDelegate = mockedNavigator;
when(() => mockedNavigator.pushNamed(AgileSmellsResults.route, arguments: any(named: 'arguments'))).thenAnswer((_) async => const AgileSmellsResults(validatedSmellCards: []));
}
}