I,m unit testing flutter class using mockito. I stubbed one method using 'when()' but it returns null. is there something wrong in my testing?. I have used freezed union to generate Result class. My Repository is an abstract class
this is my test class
class MockRepository extends Mock implements Repository {}
void main() {
late CryptoUseCases useCases;
late MockRepository repository;
final Result<List<Crypto>, Exception> data = const Result.success([
Crypto(
id: 1,
name: 'Bitcoin',
symbol: 'BTC',
priceUsd: 4000,
availableSupply: 879787908,
logo: '',
volumeUsd24h: 786876,
totalSupply: 876587,
marketCapUsd: 698,
maxSupply: 867987,
rank: 1,
),
Crypto(
id: 3,
name: 'Euthereum',
symbol: 'ETH',
priceUsd: 134,
availableSupply: 879787908,
logo: '',
volumeUsd24h: 786876,
totalSupply: 876587,
marketCapUsd: 698,
maxSupply: 867987,
rank: 2,
),
]);
setUp(() {
repository = MockRepository();
useCases = CryptoUseCases(repository);
});
test('getCryptos return a list of crypto', () async {
//arrange
when(repository.getCryptos()).thenAnswer((_) async => data);
//act
final result = await useCases.getCryptos();
//assert
expect(result, equals(data));
verify(repository.getCryptos()).called(1);
verifyNoMoreInteractions(repository);
});
}
this is my class
class CryptoUseCases {
final Repository repository;
CryptoUseCases(this.repository);
Future<Result<List<Crypto>, Exception>> getCryptos() async {
final result = await repository.getCryptos();
result.when(success: (data) {
return Result.success(data);
}, error: (e) {
return Result.error(e);
});
return Result.error(Exception());
}
}
i'm using freezed here. is that a problem?
this is the error
type 'Null' is not a subtype of type 'Future<Result<List<Crypto>, Exception>>'
package:crypto_app/src/domain/repositories/repository.dart 6:43 MockRepository.getCryptos
test\use_cases_test.dart 51:21 main.<fn>
test\use_cases_test.dart 49:46
found the answer after some tries.
I believe the null error is caused due to null safe dart feature.
So to create a mock for null safe dart, we need to anotate @GenerateMocks() above the main method of test.
In my case
and use buildrunner to generate code.
after this, this code worked fine