我在使用bloc_test和Mockito时遇到了一些问题。我有一个具有用例依赖关系的块,我正在创建一个具有测试值的用例模拟。
这是我的地盘
class IssuesBloc extends Bloc<IssuesEvent, IssuesState> {
final GetIssues _getIssues;
IssuesBloc(this._getIssues) : super(IssuesInitial());
@override
Stream<IssuesState> mapEventToState(
IssuesEvent event,
) async* {
// here is my action code that is not the necesary to show for the question of my bloc
}
}
这是我的bloc mockito(我不确定如何将mockito用例传递给MockIssuesBloc):
class MockIssuesBloc extends MockBloc<IssuesState> implements IssuesBloc {}
这是我的用例,其中包含要测试的数据列表:
class MockGetIssues extends Mock implements GetIssues {
Future<Either<AppError, List<IssuesModel>>> call(
PageParams pageParams) async {
return Future.delayed(
const Duration(
milliseconds: 100,
),
() => right(
[
IssuesModel(id: 1),
IssuesModel(id: 2),
IssuesModel(id: 3),
IssuesModel(id: 4),
IssuesModel(id: 5),
IssuesModel(id: 6),
IssuesModel(id: 7),
IssuesModel(id: 8),
IssuesModel(id: 9),
IssuesModel(id: 10),
IssuesModel(id: 11),
IssuesModel(id: 12),
IssuesModel(id: 13),
IssuesModel(id: 14),
IssuesModel(id: 15),
IssuesModel(id: 16),
IssuesModel(id: 17),
IssuesModel(id: 18),
IssuesModel(id: 19),
IssuesModel(id: 20),
].getRange(0, pageParams.take),
),
);
}
}
这是我的测试主要(我有3种不同的方式,并得到错误的3):
void main() {
group('IssuesBloc', () {
MockIssuesBloc issuesBloc;
MockGetIssues mockGetIssues;
setUpAll(() {
mockGetIssues = MockGetIssues();
issuesBloc = MockIssuesBloc();
});
blocTest( // throws Bad state: Mock method was not called within `when()`. Was a real method called?
'bloc: emits [IssuesInitial(), IssuesLoadedState(),] when successful',
build: () {
when(getIssues(PageParams()))
.thenAnswer((value) async => right([IssuesModel(id: 1)]));
return IssuesBloc(getIssues);
},
act: (bloc) => bloc.add(LoadIssues()),
expect: [
IssuesInitial(),
isA<IssuesLoadedState>(),
],
);
// Bad state: Mock method was not called within `when()`. Was a real method called?
test('when: emits [IssuesInitial(), IssuesLoadedState(),] when successful', () {
when(mockGetIssues(PageParams()))
.thenAnswer((value) async => right([IssuesModel(id: 1)]));
final bloc = IssuesBloc(mockGetIssues);
bloc.add(LoadIssues());
emitsExactly(bloc, [
IssuesInitial(),
isA<IssuesLoadedState>(),
]);
});
// type '_BroadcastSubscription<Type>' is not a subtype of type 'StreamSubscription<IssuesState>'
test("whenListen: emits [IssuesInitial(), IssuesLoadedState(),] when successful", () {
whenListen(
issuesBloc,
Stream.fromIterable([IssuesInitial]),
);
expectLater(
issuesBloc,
emitsInOrder(
[
IssuesInitial,
isA<IssuesLoadedState>()
],
),
);
});
});
}
我还使用了bloc而没有使用mockito,在这3种情况下,我得到了下一个错误:错误状态:未在when()
中调用Mock方法。是否调用了真实的方法?我不确定为什么会遇到此问题
1条答案
按热度按时间w80xi6nr1#
MockBloc提供的底层mock是Mocktail包(https://pub.dev/packages/mocktail)中的一个mock。
您需要使用Mocktail的
when
来存根这些mock。Mockito也提供了一个when
方法,但是它是不兼容的(因此您收到了运行时错误)。