Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Dart Tutorial

Dart HOME Dart Intro Dart Get Started Dart Syntax Dart Output Dart Comments Dart Variables Dart final and const Dart Data Types Dart Numbers Dart Strings Dart String Interpolation Dart String Methods Dart Booleans Dart Type Conversion Dart Null Safety Dart late Dart Operators Dart Arithmetic Dart Assignment Dart Comparison Dart Logical Dart Type Test Dart Null Operators Dart Cascade Dart If...Else Dart Switch Dart While Loop Dart For Loop Dart Break/Continue

Dart Collections

Dart Lists Dart Access List Items Dart Change List Items Dart Loop Lists Dart List Methods Dart Sets Dart Maps Dart Access Map Items Dart Loop Maps Dart Collection if/for Dart Spread Operator

Dart Functions

Dart Functions Dart Parameters Dart Named Parameters Dart Return Values Dart Arrow Functions Dart Anonymous Functions Dart Closures Dart Scope Dart Recursion

Dart Classes

Dart OOP Dart Classes/Objects Dart Constructors Dart Named Constructors Dart Factory Constructors Dart Getters and Setters Dart Static Members Dart Inheritance Dart Abstract Classes Dart Interfaces Dart Mixins Dart Extension Methods Dart Enums Dart Generics

Dart 3 Features

Dart Records Dart Patterns Dart Switch Expressions Dart Sealed Classes Dart Class Modifiers

Dart Errors

Dart Exceptions Dart Custom Exceptions

Dart Async

Dart Async Intro Dart Futures Dart async/await Dart Streams Dart Isolates

Dart Libraries

Dart Imports Dart Packages Dart Math Dart Dates Dart JSON Dart RegExp Dart User Input Dart Files Dart Testing

Dart Examples

Dart Examples Dart Exercises


Dart Testing


Share

Dart Testing

A test is a small piece of code that checks that your code works.

When you change your code later, you run the tests again, and they tell you if something broke.

Dart uses the test package for this.

A project made with dart create already has the test package and a test folder.

Note: Tests use a package from pub.dev, so they do not work in our "Try it Yourself" editor.

Run the examples on this page in a project on your own computer, see Dart Packages.


The Code to Test

We will test these functions in the file lib/my_app.dart:

Example

lib/my_app.dart

int add(int a, int b) {
  return a + b;
}

String greet(String name) {
  return 'Hello, $name!';
}

double average(List<int> numbers) {
  if (numbers.isEmpty) {
    throw ArgumentError('The list is empty');
  }
  return numbers.reduce((a, b) => a + b) / numbers.length;
}


Write a Test

Test files are in the test folder, and their names end with _test.dart:

Example

test/my_app_test.dart

import 'package:my_app/my_app.dart';
import 'package:test/test.dart';

void main() {
  test('add() adds two numbers', () {
    expect(add(2, 3), 5);
  });

  test('greet() says hello', () {
    expect(greet('Anna'), 'Hello, Anna!');
  });
}
  • test() makes one test: a description and a function with the code to check
  • expect(actual, expected) checks that the first value matches the second value

Run all the tests with dart test:

Example

dart test

Result:

00:00 +0: loading test\my_app_test.dart
00:00 +0: test\my_app_test.dart: add() adds two numbers
00:00 +1: test\my_app_test.dart: greet() says hello
00:00 +2: All tests passed!

The number after + counts the tests that passed.


A Failing Test

This test expects the wrong result, so it fails:

Example

test/fail_test.dart

import 'package:my_app/my_app.dart';
import 'package:test/test.dart';

void main() {
  test('add() adds two numbers', () {
    expect(add(2, 2), 5);
  });
}

You can run one test file by adding its name:

Example

dart test test/fail_test.dart

Result:

00:00 +0: loading test/fail_test.dart
00:00 +0: add() adds two numbers
00:00 +0 -1: add() adds two numbers [E]
  Expected: <5>
    Actual: <4>

  package:matcher          expect
  test\fail_test.dart 6:5  main.<fn>

00:00 +0 -1: Some tests failed.

Failing tests:
  test/fail_test.dart: add() adds two numbers

-1 means that one test failed.

The output shows the expected value, the actual value, and the line of the test that failed (line 6).


Groups and Matchers

Use group() to put tests that belong together under one name.

The second value in expect() can also be a matcher: a check like "greater than 12" or "contains 2".

Example

test/group_test.dart

import 'package:my_app/my_app.dart';
import 'package:test/test.dart';

void main() {
  group('average()', () {
    test('of three numbers', () {
      expect(average([2, 4, 6]), 4.0);
    });

    test('of one number', () {
      expect(average([7]), 7.0);
    });

    test('of an empty list throws an error', () {
      expect(() => average([]), throwsArgumentError);
    });
  });

  group('matchers', () {
    test('compare numbers', () {
      expect(add(10, 5), greaterThan(12));
      expect(average([1, 2]), closeTo(1.5, 0.01));
    });

    test('check strings and lists', () {
      expect(greet('Tom'), startsWith('Hello'));
      expect(greet('Tom'), contains('Tom'));
      expect([1, 2, 3], contains(2));
      expect([1, 2, 3], hasLength(3));
      expect(<int>[], isEmpty);
    });
  });
}

Result:

00:00 +0: loading test/group_test.dart
00:00 +0: average() of three numbers
00:00 +1: average() of one number
00:00 +2: average() of an empty list throws an error
00:00 +3: matchers compare numbers
00:00 +4: matchers check strings and lists
00:00 +5: All tests passed!

The group name is written in front of each test name.

To test that code throws an error, put the code in a function: () => average([]).

Some useful matchers:

MatcherChecks that the value
equals(x)is equal to x (the same as writing x)
greaterThan(x), lessThan(x)is bigger or smaller than x
closeTo(x, delta)is a number near x
contains(x)contains x (a string, a list or a map)
startsWith(x), endsWith(x)is a string that starts or ends with x
hasLength(n)has n items or characters
isEmpty, isNotEmptyis empty or not empty
isNull, isNotNullis null or not null
isA<T>()has the type T
throwsArgumentError, throwsA(...)is a function that throws an error

Run Code Before Each Test

setUp() runs a function before every test.

Use it to give each test fresh data, so the tests do not change each other's data:

Example

test/setup_test.dart

import 'package:test/test.dart';

void main() {
  late List<String> cart;

  setUp(() {
    cart = ['Apple'];
  });

  test('add an item', () {
    cart.add('Banana');
    expect(cart, ['Apple', 'Banana']);
  });

  test('every test gets a new cart', () {
    expect(cart, ['Apple']);
  });
}

Result:

00:00 +0: loading test/setup_test.dart
00:00 +0: add an item
00:00 +1: every test gets a new cart
00:00 +2: All tests passed!

The first test added 'Banana', but the second test still gets a cart with only 'Apple'.

tearDown() works the same way, but runs after every test.

To run only the tests whose name contains a word, use --name:

Example

dart test --name "empty"


Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.