Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Dart Unit Testing

Dart Unit Testing

Unit testing is a fundamental means of ensuring code quality.

It verifies whether the behavior of each smallest functional unit (usually a function or method) meets expectations.

This chapter introduces the use of Dart's test package, writing test() test cases, expect assertions, and group() grouped tests.


Installation and Configuration of the test Package

Dart officially provides the test package for writing and running tests.

First, add the dependency in pubspec.yaml:



# File path: pubspec.yaml

dev_dependencies:

  test: ^1.24.0

Then run the following command to install:



$ dart pub get

Test files are usually placed in the project's test/ directory, with filenames ending in _test.dart.

A typical project structure:



my_project/

├── lib/

│   └── calculator.dart       # 被测试的代码

├── test/

│   └── calculator_test.dart  # 测试文件

└── pubspec.yaml


Writing test() Test Cases

The test() function is the basic unit for writing test cases.

It takes two parameters: a test description (a string) and the test function body.

Example

The code under test (lib/calculator.dart):

// file path: lib/calculator.dart

class

Calculator

{

 

int

add

(

int

a

,

int

b

)

=>

a

b

;

 

int

subtract

(

int

a

,

int

b

)

=>

a

b

;

 

int

multiply

(

int

a

,

int

b

)

=>

a

b

;

 

double

divide

(

int

a

,

int

b

)

{

   

if

(

b

==

0

)

{

     

throw

ArgumentError

(

'Divisor cannot be 0'

)

;

   

}

   

return

a

/

b

;

 

}

 

bool

isEven

(

int

n

)

=>

n

%

2

==

0

;

  List

<

int

filterPositive

(

List

<

int

numbers

)

{

return

numbers.

where

(

(

n

)

=>

n

0

)

.

toList

(

)

;

 

}

}

Example

The test file (test/calculator_test.dart):

// file path: test/calculator_test.dart

import

'package:test/test.dart'

;

import

'package:my_project/calculator.dart'

;

void

main

(

)

{

 

// create a Calculator instance for testing

 

var

calculator

=

Calculator

(

)

;

 

// test() function: the first parameter is the test description, the second is the test function

  test

(

'add() adds two positive numbers'

,

(

)

{

   

var

result

=

calculator.

add

(

3

,

5

)

;

   

// expect() assertion: verify whether the actual result equals the expected value

    expect

(

result

,

equals

(

8

)

)

;

 

}

)

;

  test

(

'add() adds numbers including negatives'

,

(

)

{

    expect

(

calculator.

add

(

3

,

5

)

,

equals

(

2

)

)

;

    expect

(

calculator.

add

(

3

,

5

)

,

equals

(

8

)

)

;

 

}

)

;

  test

(

'subtract() subtraction operation'

,

(

)

{

    expect

(

calculator.

subtract

(

10

,

3

)

,

equals

(

7

)

)

;

 

}

)

;

  test

(

'multiply() multiplication operation'

,

(

)

{

    expect

(

calculator.

multiply

(

4

,

5

)

,

equals

(

20

)

)

;

   

// multiply by zero

    expect

(

calculator.

multiply

(

100

,

0

)

,

equals

(

0

)

)

;

 

}

)

;

  test

(

'divide() normal division'

,

(

)

{

    expect

(

calculator.

divide

(

10

,

2

)

,

equals

(

5.0

)

)

;

    expect

(

calculator.

divide

(

7

,

2

)

,

equals

(

3.5

)

)

;

 

}

)

;

  test

(

'isEven() even number check'

,

(

)

{

    expect

(

calculator.

isEven

(

4

)

,

isTrue

)

;

    expect

(

calculator.

isEven

(

5

)

,

isFalse

)

;

 

}

)

;

}

Run the tests:



$ dart test



00:00 +6: All tests passed!


expect Assertions

expect() is the most core function in testing; it verifies whether the actual value satisfies a certain condition.

Basic syntax: expect(actual, matcher).

Common Matchers

Matcher Purpose Example
equals(expected) Verify value equality expect(result, equals(42))
isTrue / isFalse Verify boolean values expect(flag, isTrue)
isNull / isNotNull Verify null expect(value, isNull)
contains(value) Contains a certain element (list) or substring (string) expect(list, contains('a'))
isA() Verify type expect(obj, isA())
throws() Verify an exception is thrown expect(() => f(), throwsException)
isNotEmpty non-null expect(list, isNotEmpty)
hasLength(n) Verify length expect(list, hasLength(3))
greaterThan(n) Greater than expect(score, greaterThan(60))
closeTo(value, delta) Floating-point approximate equality expect(3.14, closeTo(3.1, 0.1))

Example

Practical applications of various Matchers:

import

'package:test/test.dart'

;

void

main

(

)

{

  test

(

'RUNOOB Various Assertion Examples'

,

(

)

{

   

// basic equality

    expect

(

2

2

,

equals

(

4

)

)

;

   

// boolean values

    expect

(

'hello'

.

contains

(

'h'

)

,

isTrue

)

;

    expect

(

''

.

isEmpty

,

isTrue

)

;

   

// null check

    String

?

name

;

    expect

(

name

,

isNull

)

;

    name

=

'RUNOOB'

;

    expect

(

name

,

isNotNull

)

;

   

// Type checking

    expect

(

'RUNOOB'

,

isA

<

String

(

)

)

;

    expect

(

42

,

isA

<

int

(

)

)

;

   

// list/string contains

    expect

(

[

1

,

2

,

3

]

,

contains

(

2

)

)

;

    expect

(

'Hello, RUNOOB!'

,

contains

(

'RUNOOB'

)

)

;

   

// length

    expect

(

[

1

,

2

,

3

]

,

hasLength

(

3

)

)

;

    expect

(

'Dart'

,

hasLength

(

4

)

)

;

   

// numeric comparison

    expect

(

100

,

greaterThan

(

50

)

)

;

    expect

(

30

,

lessThan

(

60

)

)

;

    expect

(

75

,

greaterThanOrEqualTo

(

60

)

)

;

   

// floating-point comparison (avoid precision issues)

    expect

(

0.1

0.2

,

closeTo

(

0.3

,

0.001

)

)

;

   

// collection is non-empty

    expect

(

[

1

,

2

]

,

isNotEmpty

)

;

   

// list equality

    expect

(

[

1

,

2

,

3

]

,

equals

(

[

1

,

2

,

3

]

)

)

;

   

// Map contains a certain key

   

var

user

=

{

'name'

:

'runoob'

,

'age'

:

10

}

;

    expect

(

user

,

containsPair

(

'name'

,

'runoob'

)

)

;

    expect

(

user.

keys

,

contains

(

'age'

)

)

;

 

}

)

;

}



00:00 +1: All tests passed!

Testing Exceptions

Example

import

'package:test/test.dart'

;

int

divide

(

int

a

,

int

b

)

{

 

if

(

b

==

0

)

throw

ArgumentError

(

'Divisor cannot be 0'

)

;

 

return

a

~/

b

;

}

void

main

(

)

{

  test

(

'divide() should throw an exception when dividing by zero'

,

(

)

{

   

// verify that any exception is thrown

    expect

(

(

)

=>

divide

(

10

,

0

)

,

throwsException

)

;

   

// verify that a specific type of exception is thrown

    expect

(

(

)

=>

divide

(

10

,

0

)

,

throwsArgumentError

)

;

   

// verify the exception message

    expect

(

     

(

)

=>

divide

(

10

,

0

)

,

      throwsA

(

predicate

(

(

e

)

=>

          e

is

ArgumentError

&&

          e.

message

.

contains

(

'Divisor'

)

)

)

,

   

)

;

 

}

)

;

  test

(

'divide() does not throw in normal cases'

,

(

)

{

    expect

(

(

)

=>

divide

(

10

,

2

)

,

returnsNormally

)

;

    expect

(

divide

(

10

,

2

)

,

equals

(

5

)

)

;

 

}

)

;

}



00:00 +2: All tests passed!

When testing exceptions, you need to wrap the code that may throw in an anonymous function (() => code) instead of calling it directly. If you write expect(divide(10, 0), throwsException) directly, divide will throw immediately and expect never gets a chance to run.


Grouped Tests group()

group() is used to organize related test cases together, making the test structure clearer.

Example

import

'package:test/test.dart'

;

// the function under test

class

StringUtils

{

 

static

String capitalize

(

String s

)

{

   

if

(

s.

isEmpty

)

return

s

;

   

return

s

[

0

]

.

toUpperCase

(

)

s.

substring

(

1

)

;

 

}

 

static

String reverse

(

String s

)

{

   

return

s.

split

(

''

)

.

reversed

.

join

(

''

)

;

 

}

 

static

bool

isPalindrome

(

String s

)

{

   

var

clean

=

s.

toLowerCase

(

)

.

replaceAll

(

' '

,

''

)

;

   

return

clean

==

reverse

(

clean

)

;

 

}

 

static

int

countWords

(

String s

)

{

   

if

(

s.

trim

(

)

.

isEmpty

)

return

0

;

   

return

s.

trim

(

)

.

split

(

RegExp

(

r

'\s+'

)

)

.

length

;

 

}

}

void

main

(

)

{

 

// group() nests and organizes tests

  group

(

'StringUtils'

,

(

)

{

   

// subgroup

    group

(

'capitalize()'

,

(

)

{

      test

(

'capitalize the first letter of a normal word'

,

(

)

{

        expect

(

StringUtils.

capitalize

(

'hello'

)

,

equals

(

'Hello'

)

)

;

     

}

)

;

      test

(

'an already capitalized word stays unchanged'

,

(

)

{

        expect

(

StringUtils.

capitalize

(

'Hello'

)

,

equals

(

'Hello'

)

)

;

     

}

)

;

      test

(

'an empty string returns an empty string'

,

(

)

{

        expect

(

StringUtils.

capitalize

(

''

)

,

equals

(

''

)

)

;

     

}

)

;

      test

(

'a single character'

,

(

)

{

        expect

(

StringUtils.

capitalize

(

'a'

)

,

equals

(

'A'

)

)

;

     

}

)

;

   

}

)

;

    group

(

'reverse()'

,

(

)

{

      test

(

'reverse a normal string'

,

(

)

{

        expect

(

StringUtils.

reverse

(

'RUNOOB'

)

,

equals

(

'BOONUR'

)

)

;

     

}

)

;

      test

(

'reversing a palindrome string stays unchanged'

,

(

)

{

        expect

(

StringUtils.

reverse

(

'aba'

)

,

equals

(

'aba'

)

)

;

     

}

)

;

      test

(

'empty string'

,

(

)

{

        expect

(

StringUtils.

reverse

(

''

)

,

equals

(

''

)

)

;

     

}

)

;

   

}

)

;

    group

(

'isPalindrome()'

,

(

)

{

      test

(

'a palindrome string returns true'

,

(

)

{

        expect

(

StringUtils.

isPalindrome

(

'racecar'

)

,

isTrue

)

;

        expect

(

StringUtils.

isPalindrome

(

'A man a plan a canal Panama'

)

,

isTrue

)

;

     

}

)

;

      test

(

'a non-palindrome string returns false'

,

(

)

{

        expect

(

StringUtils.

isPalindrome

(

'hello'

)

,

isFalse

)

;

     

}

)

;

      test

(

'an empty string is treated as a palindrome'

,

(

)

{

        expect

(

StringUtils.

isPalindrome

(

''

)

,

isTrue

)

;

     

}

)

;

   

}

)

;

    group

(

'countWords()'

,

(

)

{

      test

(

'a normal sentence'

,

(

)

{

        expect

(

StringUtils.

countWords

(

'Hello World Dart'

)

,

equals

(

3

)

)

;

     

}

)

;

      test

(

'extra spaces'

,

(

)

{

        expect

(

StringUtils.

countWords

(

'  Hello   World  '

)

,

equals

(

2

)

)

;

     

}

)

;

      test

(

'empty string'

,

(

)

{

        expect

(

StringUtils.

countWords

(

''

)

,

equals

(

0

)

)

;

        expect

(

StringUtils.

countWords

(

'   '

)

,

equals

(

0

)

)

;

     

}

)

;

   

}

)

;

 

}

)

;

}



00:00 +12: All tests passed!

group() can be nested to create a hierarchical test structure.

This makes test reports easier to read and helps quickly locate failing tests.

A good grouping strategy is to organize by "the module/class/method under test". This way, when a test fails, you immediately know which feature has a problem.

setUp and tearDown

setUp runs before each test, and tearDown runs after each test.

They are used to prepare the test environment and clean up resources.

Example

import

'package:test/test.dart'

;

// simulate a class that needs initialization and cleanup

class

Database

{

 

bool

isConnected

=

false

;

 

void

connect

(

)

{

    isConnected

=

true

;

    print

(

' Database connected'

)

;

 

}

 

void

disconnect

(

)

{

    isConnected

=

false

;

    print

(

' Database disconnected'

)

;

 

}

  String query

(

String sql

)

{

   

if

(

!

isConnected

)

throw

Exception

(

'Database not connected'

)

;

   

return

'Query result: $sql'

;

 

}

}

void

main

(

)

{

  group

(

'Database test'

,

(

)

{

    late Database db

;

 

// late initialization

   

// executed before each test

    setUp

(

(

)

{

      db

=

Database

(

)

;

      db.

connect

(

)

;

      print

(

' [setUp] prepare the test environment'

)

;

   

}

)

;

   

// executed after each test

    tearDown

(

(

)

{

      db.

disconnect

(

)

;

      print

(

' [tearDown] clean up the test environment'

)

;

   

}

)

;

    test

(

'query() normal query'

,

(

)

{

     

var

result

=

db.

query

(

'SELECT * FROM users'

)

;

      expect

(

result

,

contains

(

'RUNOOB'

)

?

result.

contains

(

'users'

)

:

result.

contains

(

'users'

)

)

;

     

// simplified assertion

      expect

(

result

,

isNotEmpty

)

;

   

}

)

;

    test

(

'query() can run multiple queries after connecting'

,

(

)

{

     

var

r1

=

db.

query

(

'SELECT 1'

)

;

     

var

r2

=

db.

query

(

'SELECT 2'

)

;

      expect

(

r1

,

isNotEmpty

)

;

      expect

(

r2

,

isNotEmpty

)

;

   

}

)

;

    test

(

'querying while not connected throws an exception'

,

(

)

{

      db.

disconnect

(

)

;

 

// disconnect manually

      expect

(

(

)

=>

db.

query

(

'SELECT 1'

)

,

throwsException

)

;

   

}

)

;

 

}

)

;

}



  数据库已连接

  [setUp] 准备测试环境

  数据库已断开

  [tearDown] 清理测试环境

  数据库已连接

  [setUp] 准备测试环境

  数据库已断开

  [tearDown] 清理测试环境

  数据库已连接

  [setUp] 准备测试环境

  数据库已断开

  [tearDown] 清理测试环境

00:00 +3: All tests passed!

Note the execution order of setUp and tearDown in the output--each runs once before and after every test.

setUp and tearDown ensure each test starts from a clean state, unaffected by other tests. This is the key guarantee of test independence.


Asynchronous Tests

Dart's test package natively supports asynchronous tests.

Test functions can return a Future, and the framework automatically waits for the Future to complete.

Example

import

'package:test/test.dart'

;

// asynchronous function: simulate a network request

Future

<

String

fetchUserData

(

int

userId

)

async

{

  await Future.

delayed

(

Duration

(

milliseconds

:

100

)

)

;

 

if

(

userId

<=

0

)

{

   

throw

Exception

(

'Invalid user ID'

)

;

 

}

 

return

'Data of user $userId'

;

}

Future

<

List

<

int

fetchNumbers

(

)

async

{

  await Future.

delayed

(

Duration

(

milliseconds

:

50

)

)

;

 

return

[

1

,

2

,

3

,

4

,

5

]

;

}

void

main

(

)

{

  group

(

'Asynchronous test'

,

(

)

{

    test

(

'fetchUserData() fetches data normally'

,

(

)

async

{

     

var

data

=

await fetchUserData

(

1

)

;

      expect

(

data

,

equals

(

'Data of user 1'

)

)

;

   

}

)

;

    test

(

'fetchUserData() throws on an invalid ID'

,

(

)

async

{

      expect

(

       

(

)

=>

fetchUserData

(

1

)

,

        throwsA

(

isA

<

Exception

(

)

)

,

)

;

   

}

)

;

    test

(

'fetchNumbers() returns the correct list'

,

(

)

async

{

     

var

numbers

=

await fetchNumbers

(

)

;

      expect

(

numbers

,

hasLength

(

5

)

)

;

      expect

(

numbers

,

contains

(

3

)

)

;

      expect

(

numbers.

first

,

equals

(

1

)

)

;

   

}

)

;

   

// testing multiple asynchronous operations

    test

(

'consecutive asynchronous operations'

,

(

)

async

{

     

var

data1

=

await fetchUserData

(

1

)

;

     

var

data2

=

await fetchUserData

(

2

)

;

      expect

(

data1

,

isNot

(

equals

(

data2

)

)

)

;

      expect

(

data1

,

contains

(

'1'

)

)

;

      expect

(

data2

,

contains

(

'2'

)

)

;

   

}

)

;

 

}

)

;

}



00:00 +4: All tests passed!


Common commands for running tests

Command Function
dart test Run all tests
dart test test/calculator_test.dart Run a specific test file
dart test --name="add" Run only tests whose name contains "add"
dart test --concurrency=4 Run tests concurrently (speed up)
dart test --reporter=expanded Verbose output mode
dart test --coverage=coverage Generate test coverage data

Testing Best Practices

Practice Description
Each test verifies only one thing One test() corresponds to one behavior, making failures faster to locate
Test names describe behavior rather than implementation "add() adds two positive numbers" is better than "add() test"
AAA Pattern Arrange (Prepare) -> Act (Execute) -> Assert (Assert)
Write a failing test first Confirm the test catches the error, then write code to make it pass
Boundary condition testing Null values, zero, negative numbers, extremely large values, extremely small values
Keep tests independent of each other The result of one test should not affect another test

Tests are not a burden but insurance. The more tests you write, the more confidence you have when refactoring. When a test fails, you don't need to guess where the problem is--the test tells you precisely.


Chapter Summary

This chapter introduced the complete flow of Dart unit testing: installing the test package, writing test() test cases, using expect assertions, group() grouping, setUp/tearDown environment management, and asynchronous testing.

Unit testing is a required course for professional developers; forming the habit of writing tests will continuously improve your code quality.


Full Tutorial Summary

Congratulations on completing the introductory study of the Dart programming language!

Let's review the learning path of these 21 chapters:

Stage Section Core Content
I. Getting Started Basics Chapters 1-4 Dart overview, environment setup, first program, basic syntax
II. Core Types and Control Flow Chapters 5-8 Variables and data types, operators, control flow, collections
III. Functions and Object Orientation Chapters 9-13 Functions, classes and objects, inheritance and polymorphism, interfaces and Mixins, generics
IV. Advanced Features Chapters 14-17 Enums and symbols, exception handling, package and library management, typedef
V. Asynchronous Programming and Testing Chapters 18-21 Asynchronous programming, Stream, concurrency and Isolate, unit testing

Having mastered this content, you now have the ability to use Dart for everyday development.

Next you can dive deeper into The Flutter framework, applying your Dart knowledge to UI development for mobile and Web.