9
votes

I'm working on a Flutter project and trying to find the best way to structure my tests. Typically I structure tests to mirror the directory structure of the main project which is being tested.

lib
 |models
 |providers
   |userprovider.dart
test
 lib
   |models
   |providers
     |userproviderShould.dart  

However, I'm having trouble figuring out if this approach is less than optimal for the Dart code. Each file in the test project seems to need to have a main method, which feels odd. I'm also not clear on how to run the entire test suite. The Flutter test running (flutter test) doesn't seem to understand directories. Running flutter test test/lib/providers doesn't work while flutter test test/lib/providers/userproviderShould.dart does. If it doesn't understand directories it certainly doesn't understand having to recurse into directories.

Is there a way to solve this that doesn't involve either having to build a fragile entry point that manually includes all the rest of the tests or writing a shell script to go run each file individually?

3

3 Answers

23
votes

If you want flutter test or pub run test to execute a file without manually passing its path as parameter to the command, then the file must:

  • be inside the /test folder
  • its name must be suffixed by _test.dart

Anything that does not have this _test will not be executed by the command line.

8
votes

To run all the unit tests in a project, type one of the following commands in the terminal while in the root of your project:

Flutter project

flutter test

Dart project

dart test

Notes

  • Dart projects used to be pub run test. You can probably still do that but dart test is the new way to do it and is also easier to remember.
  • test package documentation
  • You may need to run flutter pub get or dart pub get to retrieve the test package if you haven't previously.
0
votes

With Flutter 2.5 (and perhaps below, though I haven't checked), apparently, you can use any directory name as an argument and it'll run all **/*_test.dart files in it.

So: flutter test lib does the trick! You can pass additional arguments to the command, as long as the directory name is the very last argument (flutter test --no-pub --coverage lib).

Docs: https://pub.dev/packages/test#running-tests