我正在使用Bloc模式,现在我要测试UI。我的问题是:如何模拟流? 这是我拥有的代码: 我给RootPage类一个可选的mockBloc值,如果这个mockBloc不为空,我会将它设置为实际的_bloc。
class RootPage extends StatefulWidget {
final loggedOut;
final mockBlock;
RootPage(this.loggedOut, {this.mockBlock});
@override
_RootPageState createState() => _RootPageState();
}
class _RootPageState extends State<RootPage> {
LoginBloc _bloc;
@override
void initState() {
super.initState();
if (widget.mockBlock != null)
_bloc = widget.mockBlock;
else
_bloc = new LoginBloc();
if (widget.loggedOut == false)
_bloc.startLoad.add(null);
}
...
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: _bloc.load,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(
children: <Widget>
...
这是我尝试过的内容:
testWidgets('MyWidget', (WidgetTester tester) async {
MockBloc mockBloc = new MockBloc();
MockTokenApi mockTokenApi = new MockTokenApi();
await tester.pumpWidget(new MaterialApp(
home: RootPage(false, mockBlock: mockBloc)));
when(mockBloc.startLoad.add(null)).thenReturn(mockBloc.insertLoadStatus.add(SettingsStatus.set)); //this will give in output the stream that the StreamBuilder is listening to (_bloc.load)
});
await tester.pump();
expect(find.text("Root"), findsOneWidget);
});
我所得到的结果总是:
当调用调用了空对象上的 'add' 方法
_bloc.startLoad.add(null)
时。