How to import test util files inside of your tests on Dart/Flutter

2.3k views Asked by At

I have some unit tests and some classes that are related only to tests, like factories for my models, some extensions on mockito and others...

The issue is when I try to import those files from my tests I can just import them with relative paths, lets say I have this utilities:

  • test/src/test_utils/factories.dart
  • test/src/test_utils/mocks.dart
  • test/src/test_utils/mockito_extensions.dart

How I can not do it

But When I try to import them from my tests It can not find them with

import 'package:myapp/test_utils/mocks.dart';

or:

import 'package:myapp/src/test_utils/mocks.dart';

The only one that works

The only way to import them is by relative paths like:

import '../../test_utils/mocks.dart';

The question

I would love to understand what is happening here, why my tests cant find the test utils class on the imports and whats the best way to do this.

1

There are 1 answers

0
Nate Bosch On BEST ANSWER

In the pub package layout the package: URI format is used for files under lib/. These are the "public libraries" that can be used from outside the package, and so they are the ones associated with the package name. Files under test/ are private to the package and don't need to be referenced by package name - they only can be referenced from neighboring files and directories so a relative import is sufficient. The package: URI format is designed primarily because it allows imports to other packages, to which there is no stable relative path.

See https://dart.dev/tools/pub/package-layout#public-libraries

Using relative imports is the recommended approach.