Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 670
Daniel Gomez Rico Avatar asked Oct 27 '25 06:10

Daniel Gomez Rico


1 Answers

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.

like image 132
Nate Bosch Avatar answered Oct 29 '25 21:10

Nate Bosch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!