gpt4 book ai didi

testing - Flutter:如何模拟 Bloc

转载 作者:IT王子 更新时间:2023-10-29 06:34:16 24 4
gpt4 key购买 nike

我想模拟我的 Bloc 以测试我的观点。

例如,这是我的 Bloc:

class SearchBloc extends Bloc<SearchEvent, SearchState> {
@override
// TODO: implement initialState
SearchState get initialState => SearchStateUninitialized();

@override
Stream<SearchState> mapEventToState(SearchState currentState, SearchEvent event) async* {
if (event is UserWrites) {
yield (SearchStateInitialized.success(objects);
}
}
}

这是 View :

class _SearchViewState extends State<SearchView> {
final TextEditingController _filterController = new TextEditingController();

@override
void initState() {
_filterController.addListener(() {
widget._searchBloc.dispatch(FetchByName(_filterController.text));
}
}


TextField buildAppBarTitle(BuildContext context) {
return new TextField(
key: Key("AppBarTextField"),
controller: _filterController,
);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: buildAppBarTitle(context),),
body: buildBlocBuilder(),
);
}

BlocBuilder<SearchEvent, SearchState> buildBlocBuilder() {
return BlocBuilder(
bloc: widget._searchBloc,
builder: (context, state) {
if (state is SearchStateUninitialized) {
return Container(
key: Key("EmptyContainer"),
);
}
return buildInitializedView(state, context);
}
});

buildInitializedView(SearchStateInitialized state, BuildContext context) {
if (state.objects.isEmpty) {
return Center(child: Text("Nothing found"),);
} else {
return buildListOfCards();
}
}
}

现在,这是我的测试:

testWidgets('Should find a card when the user searches for something', (WidgetTester tester) async {

_searchView = new SearchView(_searchBloc);

when(mockService.find( name: "a")).thenAnswer((_) =>
[objects]);

await tester.pumpWidget(generateApp(_searchView));
await tester.enterText(find.byKey(Key("searchBar")), "a");
await tester.pump();

expect(find.byType(Card), findsOneWidget);
});
}

如您所见,我只是想测试一下,当用户在搜索中输入内容并且他要查找的对象存在时,应该显示一张卡片。

最佳答案

如果我没理解错的话,您是在模拟 searchBloc 使用的某些服务。我个人尝试以一种方式设计应用程序,即应用程序仅依赖于一个 bloc,而 bloc 可能依赖于其他一些服务。然后当我想做一个小部件测试时,我只需要模拟这个 Bloc 。您可以为此使用 bloc_test 包。

在 bloc_test 页面上有这个用于 stub counterBloc 的示例:

// Create a mock instance
final counterBloc = MockCounterBloc();

// Stub the bloc `Stream`
whenListen(counterBloc, Stream.fromIterable([0, 1, 2, 3]));

然而,我通常不需要 stub bloc 流,它足以发出状态,就像这样

when(counterBloc.state).thenAnswer((_) => CounterState(456));

希望这对您有所帮助。

关于testing - Flutter:如何模拟 Bloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55236184/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com