how can we verify whether a method inside a function is called or not? I have here a sample code.
class MockService extends Mock implements Service {}
class MockRepository extends Mock implements Repository {}
class Repository {
Repository({
required this.service,
});
final Service service;
Future<void> somethingFancy() async {
await service.doSomething();
}
}
class Service {
Future<void> doSomething() async {}
}
void main() {
final service = MockService();
final repository = Repository(service: service);
group('auth repository test', () {
test('test name', () async {
when(repository.somethingFancy).thenAnswer((_) => Future.value());
await repository.somethingFancy();
verify(service.doSomething).called(1);
});
});
}
if i run the test, i get this error:
type 'Null' is not a subtype of type 'Future<void>'
test/auth_repository_test.dart 20:16 MockService.doSomething
test/auth_repository_test.dart 15:19 Repository.registerUser
package:mocktail/src/mocktail.dart 210:8 when.<fn>
test/auth_repository_test.dart 29:11 main.<fn>.<fn>
===== asynchronous gap ===========================
dart:async _completeOnAsyncError
package:mocktail/src/mocktail.dart 210:8 when.<fn>
test/auth_repository_test.dart 29:11 main.<fn>.<fn>
if i change my repository variable to final repository = MockRepository();
,
i cannot inject the Service class
, so definitely the method inside service class wont be called. That's why if I run the this test:
void main() {
final service = MockService();
final repository = MockRepository();
group('auth repository test', () {
test('test name', () async {
when(repository.somethingFancy).thenAnswer((_) => Future.value());
await repository.somethingFancy();
verify(service.doSomething).called(1);
});
});
}
I get an error saying no matching calls
No matching calls (actually, no calls at all).
(If you called `verify(...).called(0);`, please instead use `verifyNever(...);`.)
package:test_api fail
package:mocktail/src/mocktail.dart 722:7 _VerifyCall._checkWith
package:mocktail/src/mocktail.dart 515:18 _makeVerify.<fn>
test/auth_repository_test.dart 32:13 main.<fn>.<fn>
What am I doing wrong here? appreciate so much help.
CodePudding user response:
You are mokking the wrong method in your test.
You have to mock answer Service#doSomething
instead of Repository#doSimethingFancy
. Check your when
statement.
test('test name', () async {
when(service.doSomething()).thenAnswer((_) => Future.value());
await repository.somethingFancy();
verify(service.doSomething).called(1);
});