mercredi 1 janvier 2020

Flutter UnitTest: Two different mocks for the same class

currently I am writing Unit tests for my mobile web application (Android app). The unit tests refer to my login system built upon Google Firebase Auth.

With one of the latest releases of the firebase authentication plugins, the return type of some functions have been changed. For example, the method firebaseAuth.signInWithEmailAndPassword has been changed from FirebaseUser to AuthResult

I have a login function in a AuthService.dart with the following content:

Future<bool> login(LoginUserData userData) async {
    try {
      _checkUserDataValidity(userData);
      final AuthResult authResult= await firebaseAuth.signInWithEmailAndPassword(email: userData.email, password: userData.password);
      return authResult.user != null;
    } catch (exception) {
      return false;
    }
  }

So, as you can see I am only checking whether the data of the user is correct or not - I am returning a boolean to check this in another file (if true is returned, the Navigator routes to another site, if wrong is returned an error message pops up).

My Unit tests for example checks for a few cases:

  1. Correct data
  2. Incorrect data (userData is not empty or null)
  3. Empty data

Example code of a test:

test('Login should work with valid user data', () async {
      when(
        firebaseAuthMock.signInWithEmailAndPassword(
          email: testValidUserData.email,
          password: testValidUserData.password,
        )
      ).thenAnswer(
        (_) => Future<AuthResultMock>.value(firebaseAuthResultMock)
      );

      final bool actionSuccess = await authService.login(testValidUserData);

      verify(
        firebaseAuthMock.signInWithEmailAndPassword(
          email: testValidUserData.email,
          password: testValidUserData.password,
        )
      ).called(1);

      expect(actionSuccess, true);
    });

To cover case one and two of my list above, I'd like to use two different Mocks. One Mock to contain a user, the other mock has no user in it.

Current issue:

(_) => Future<AuthResultMock>.value(firebaseAuthResultMock)

in my test is in conflict with this code from the AuthServie.dart

return authResult.user != null;

The mock is having null as user. How can I change this? :) Bt.w I am using Mockito.

My idea was:

  1. For correct data, to return a mock, that contains a user.
  2. For invalid data, to return a mock, that has null as user.

Thank you so much. :)

Aucun commentaire:

Enregistrer un commentaire