Generating Unit Tests

Learn how to test functions inside a BLoC using the blocTest() function.

To test the functions inside a BLoC, we use the blocTest() testing function from the bloc_test library. This function helps us run unit tests on the methods inside our BLoC.

Let’s run a signIn() function in a unit test as an example.

The AuthService mock

In unit testing, we avoid making API calls. This is because API calls are unpredictable, and unit tests should not depend on external factors. They run independently.

The signIn() function uses the AuthService to make an API request to the Firebase servers to check the credentials. We need to mock the AuthService so we can stub its functions.

  1. Add the mockito package and the build_runner package to our app as follows:
flutter pub add mockito
  1. Above the main() function in test\bloc_test.dart, add the following line:
@GenerateMocks([AuthService])
void main() {
  // ...
...