After migrating flutter code to null-safety, mock objects not accepting `any`

6,107

Solution 1

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());

Solution 2

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

Solution 3

any return null and null value is not allowed to be passed to your login method.

It's the main drawback of NNBD, the mocking is much less easy than before.

https://github.com/dart-lang/mockito/blob/master/NULL_SAFETY_README.md#problems-with-typical-mocking-and-stubbing

Share:
6,107
Arash
Author by

Arash

An enthusiastic developer specializing in Java/Kotlin and Android with +10 years of experience in software development &amp; design, who never stops learning. Here is my approach in my life "If no one can do it, I must do it" Currently having fun with #Flutter

Updated on December 28, 2022

Comments

  • Arash
    Arash over 1 year

    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.

    • Pablito
      Pablito almost 3 years
      Does my solution below solve your problem?