After the release of Flutter 2, I've migrated my code to sdk: '>=2.12.0 <3.0.0'
and all codes are "sound null safety" now. But I encountered errors in unit tests with mockito 5.0.0
e.g:
when(mockClient.login(any)).thenThrow(GrpcError.unavailable());
was ok earlier, but now, the compiler shows an error under any
, indicating:
The argument type 'Null' can't be assigned to the parameter type 'LoginRequest'
I read this link from mockito repo but I hope there is an easier way to write tests for methods with "not nullable" arguments like before.
Adding null safety to Dart and Flutter became a good solution to developer productivity issues and reduced the number of bugs. With null safety, now Flutter developers can specify which variables can be null and all the previously unnoticed errors will show up during static analysis.
We will Migrate flutter app to null safety by 3 simple steps. Step 1: First step is to check is the project is migratable or not, because we can't migrate all projects. Step 2: We need to migrate our dependency plugins. Step 3: Call Migrate project.
Welcome to null safety. This page describes how and when to migrate your code to null safety . Here are the basic steps for migrating each package that you own: Wait for the packages that you depend on to migrate. Migrate your package’s code, preferably using the interactive migration tool. Statically analyze your package’s code.
For example, the Dart and Flutter core libraries are null safe, and they’re still usable by apps that haven’t migrated to null safety. This section tells you how to check and update your package’s dependencies, with the help of the dart pub outdated command in null-safety mode.
The migration tool takes a package of null-unsafe Dart code and converts it to null safety. You can guide the tool’s conversion by adding hint markers to your Dart code. Before starting the tool, make sure you’re ready:
When assigning the Mock object, it needs to be of the Mock object type, not the BaseClass.
@GenerateMocks(MockSpec<ITransactionRepository>(as: #MockTransactionRepository),
)
void main()
{
....
ITransactionRepository baseObject = MockTransactionRepository(); // wrong
MockTransactionRepository mockObject = MockTransactionRepository(); // right
when(baseObject.method(any)); // results in compile error
when(mockObject.method(any)); // OK
...
}
Source: https://github.com/dart-lang/mockito/issues/364
See the solution here. You can use the mocktail package which makes it way easier.
With mocktail your code would become
when(() => mockClient.login(any())).thenThrow(GrpcError.unavailable());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With