Search code examples
flutterunit-testingflutter-testflutter-mockito

Where to store mock files in a flutter project?


Is there any best practice for where to store mock files in Flutter? Particularly, the auto-generated mock files, since I'm using @generateMocks annotation from Mockito package.

Should I, for example, create a package dedicated for storing all project's mocks? or keep each mock in the test package that depend on it? or are there other approaches? pro and cons?

I found some related questions for other frameworks, and although it seems like a language-agnostic issue, I'm interested in knowing whether there are any recommendations for Flutter specifically.


Solution

  • Personally, I keep the mocks with the test files that need them. So you'd have a random_test.dart and random_test.mocks.dart with the @GenerateMocks attribute in the random_test.dart file.

    Pros

    • Unlikely to conflict with others during development unless you're working in the same area
    • Easier to know where the mocks for specific tests are
    • Easier to customize mocks for different test cases

    Cons

    • Likely to have repetitive generated code
    • Longer build_runner calls, due to the repetitive generation
    • More files in the project
      • This can be somewhat mitigated by generating the files when needed instead of storing them in the repo, though that adds to the impact of the longer build_runner calls

    All in all, I don't mind the cons when put up against the easier dev cycle of just keeping the mocks with the specific tests that need them. Unless you're generating an enormous amount of mocks for each test, the extra time and repetitive generation aren't overwhelming IMO.