Flutter test : mockito GenerateMocks vs GenerateNiceMocks

Image by brgfx on Freepik

Stubbing is an important part of any developers toolkit when implementing unit testing. It helps make your unit tests run faster and more importantly allows you to run them in isolation. The most basic form of stubbing is to mock or provide canned or known answers to any calls to an object or class that we do not want to explicitly test.

At amaysim we use Flutter extensively and this article will show some examples of how we stub and mock for this framework. With Flutter one of the best packages to support stubbing is Mockito. The Flutter cookbook section on mock dependencies suggests that we use GenerateMocks annotation to create a test file with a mock:

However, if we open mockito documentation. It is suggested that we are using GenereateNiceMocks instead :

The detail of GenerateMocks and GenerateNiceMocks can be read in this documentation. Let me summarize and show you the different in practical code. We start with the class that we would like to test. We have screen to read a book. We would like to do a simple unit tests on that class.

You do not need to read the class below as a whole. Focus on the LibraryService. We are going to setup mock for LibraryService to isolate ReadScreen class unit test. After that we can compare the different between the old GenerateMocks and the new GenerateNiceMocks

The mock

Check the generated mock file and different between GenerateMocks and GenerateNiceMocks.

As you can see clearly there is new named-parameter called returnValueForMissingStub. This means with GenerateNiceMocks: all method of mocked class is stubbed even though you didn’t put the code explicitly in the unit test.

See in Action

We know now the different in code. Let us see this in action by removing the stubbing in the unit test and run the test.

GenerateNiceMocks ater stub is removed

GenerateMocks result after stub is removed

The unit test with GenerateNiceMocks will run successfully. However the unit test with GenerateMocks will throw an error for this particular test.

TL;DR

The conclusion, use GenerateNiceMocks since it will reduce your code and mistakes on unit tests. It will make your flutter unit testing more robust by stubbing all mocked class methods, even if you forget to put it. Furthermore GenerateMocks is deprecating.


Alright that’s all I have for now. If you are looking unit test android then you might want to check this awesome blog on android tests

The views expressed on this blog post are mine alone and do not necessarily reflect the views of my employer, Optus Administration Pty Ltd.

Previous
Previous

Orchestrating Multi-Domain Processes Using AWS Step Functions

Next
Next

Migrating our telephony platform to a CCaaS.