Fluttering Dart

Fluttering Dart: Unit Testing

How to write modular, efficient and bug-free code

Constantin Stan
4 min readJan 2, 2020


Photo by Louis Reed on Unsplash

Unit tests come to rescue when it comes to write performant and (almost) bug-free code.

It is not the only option for testing our code, but it is the option that allows us to test small pieces of software in isolation.

Complete code coverage doesn’t remove entirely the possibility of bugs popping-up in the code but ensures a good development cycle and more stable releases.

There are a lot of benefits provided by using unit testing:

  • early detection of bugs, and ease of debugging
  • confidence when adding new features
  • better software design, when doing test-driven development (TDD)
  • overview of our entire software system

Tests are written to confirm that code behaves as expected on normal input (the happy flow or sunny-side testing) or on non-normal input and cases (unhappy flow or rainny-side testing).

These benefits sum up and result in high quality and cost-effective code in the long run.

Dart provides some tools to handle tests and we’re going to explore those.

The Dart test package

This package is not part of the Dart SDK and has to be added as a dependency.

It can be added as one of our dev_dependencies.

test: ^1.0.0

You can find out more about Dart packages and how to add dependencies here.

With the test libraries added we can now write unit tests.

Dart unit tests

Let’s say we have a Randomizer class that returns a number within a range:

class Randomizer { 
num nextInRange(num a, num b) {
// TBI

This is how the unit test for the above method will look:

import 'package:test/test.dart';
import 'package:fluttering_dart/randomizer.dart';
void main() {
Randomizer r;
setUp(() {
r = Randomizer();