我正在编写的单元测试应该在出现异常时失败,我想匹配使用匹配器抛出的错误,但是我遇到了错误。
我目前在做什么错,这里有什么错误? 如果我做错了,为返回未来的方法测试错误方案的正确方法是什么?为什么会有异步间隙?
这是我要测试的方法:
Future<void> registerUser(String name, String email, String password) async {
auth.signUp(email, password, name).then((_) {
auth.getCurrentUser().then((user) async {
// Doing something
}).catchError((onError) {
throw onError;
});
这是我写的测试:
test('should fail to register if fetching user fails', () async {
MockAuth auth = MockAuth();
RegisterRepository repo = RegisterRepository(auth);
String password = 'password';
String email = 'email';
String name = 'name';
when(auth.signUp(email, password, name))
.thenAnswer((_) => Future.value());
when(auth.getCurrentUser()).thenThrow((_) => throw Error());
try {
await repo.registerUser(name, email, password);
fail('exception not thrown');
} catch (e) {}
verify(auth.signUp(email, password, name)).called(1);
verify(auth.getCurrentUser()).called(1);
verifyNoMoreInteractions(auth);
});
我遇到此错误:
package:mockito/src/mock.dart 403:7 PostExpectation.thenThrow.<fn>
package:mockito/src/mock.dart 130:45 Mock.noSuchMethod
package:dive/repository/register_repo.dart 25:12 RegisterRepository.registerUser.<fn>
===== asynchronous gap ===========================
dart:async Future.then
package:dive/repository/register_repo.dart 24:40 RegisterRepository.registerUser
test/repository/register_repo_test.dart 61:20 main.<fn>.<fn>
Closure: (dynamic) => Null
答案 0 :(得分:0)
对于以后遇到此问题的其他人,
Future<void> registerUser(String name, String email, String password) {
return auth
.signUp(email, password, name)
.then((_) => auth.getCurrentUser())
.then((user) {
// Doing something
}).catchError((onError) {
throw onError;
});
test('should fail to register if fetching user fails', () async {
MockAuth auth = MockAuth();
RegisterRepository repo = RegisterRepository(auth);
String password = 'password';
String email = 'email';
String name = 'name';
when(auth.signUp(email, password, name))
.thenAnswer((_) => Future.value());
when(auth.getCurrentUser()).thenAnswer((_) => Future.error('error'));
repo.registerUser(name, email, password).catchError((onError) {
expect(onError.toString(), 'error');
verify(auth.signUp(email, password, name)).called(1);
verify(auth.getCurrentUser()).called(1);
verifyNoMoreInteractions(auth);
});
});
测试现在通过。