Skip to content

Mocking dependencies | Dependency Injection Issues #568

@JuanxCursed

Description

@JuanxCursed

Hi guys!
I'm working on my firsts tests with flutter so, if I state something wrong please do not consider has a bad thing, but as an opportunity to learn more about it.

I'm trying to mock a function but I'm not able to do it.

What I expect
When I mock a class/method I expect to return the mocked values (even intercepting a dependency inside another method)

What happens
The mock is completed ignored and the class Users is instantiated and responds from the server instead of the mock. (Which make sense, but is not what I want at test level)

I'm trying to figure out the right way to proceed with these tests when working with this kind of "global" injection.

Here is how I'm "get more close" of an actual real world result:

login_controller_test.dart

@GenerateMocks([UsersUtil])
void main() {
  TestWidgetsFlutterBinding.ensureInitialized();
  initModule(LoginModule());
  LoginController login;
  MockUsersUtil users;

  setUp(() async {
    login = LoginModule.to.get<LoginController>();
    users = MockUsersUtil();
  });

  group('LoginController Test:', () {
    test("Validate instance", () {
      expect(login, isInstanceOf<LoginController>());
    });

    test('Must return a string list with emails', () async {
      when(users.userList()).thenReturn(['b@b.com']);
      List<String> user = login.getBetaListIfActive(t);
      expect(user.length, 1);
      expect(user[0], 'b@b.com');
    });
  });
}

A fake class just for testing purposes (this values come from an configuration API)
FAKE user.dart

class UsersUtil {
  List<String> userList() {
    return ['a@a.com'];
  }
}

login_controller.dart

abstract class _LoginControllerBase with Store {
  @action
  Future login() async {
    loading = true;
    try {
      List<String> betaUsers = getBetaListIfActive();
      ...
     }
   }

  ...
  List<String> getBetaListIfActive() {
    Users t = UsersUtil(); // Instead here comes our service
    List<String> users = t.userList();
    return users;
  }
}

Thanks everyone o/

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions