pubspec.yaml を書く
こんな感じ.
# pubspec.yaml
name: hello_unittest
dev_dependencies:
unittest: any
これを作業ディレクトリにおいて pub get
とコマンドを打つと, unittest
ライブラリと依存するライブラリがダウンロードされる.
Refs: http://pub.dartlang.org/doc/
$ pub get
Resolving dependencies.................
Got dependencies!
$ ls -R
packages pubspec.lock pubspec.yaml
./packages:
path stack_trace unittest
テスト対象のコードを書く
ここでは lib/hello.dart
に記述する.
// lib/hello.dart
library hello_unittest;
helloUnittest() => 'Hello, Unit Test';
テストコードを書く
test/
以下に <テスト対象>_test.dart
という名前で書くのが慣例のようだ.
// test/hello_test.dart
import 'package:unittest/unittest.dart';
import 'package:hello_unittest/hello.dart';
main() {
test('This is my first unit test.', () {
expect(helloUnittest(), equals('Hello, Unit Test'));
});
}
test/
ディレクトリを作成した時点で, もう一度 pub get
しておく.
こうすることでシンボリックリンクが生成され, test/
以下のコードから packages/
内のライブラリをインポートできるようになる.
$ pub get
Resolving dependencies...
Got dependencies!
$ ls -l test/
total 16
-rw-r--r-- 1 kkohtaka staff 204 Feb 7 03:13 hello_test.dart
lrwxr-xr-x 1 kkohtaka staff 11 Feb 7 03:13 packages -> ../packages
Refs: https://www.dartlang.org/articles/dart-unit-tests/
テストを実行する
コマンドラインから次のように実行する.
$ dart --checked test/hello_test.dart
unittest-suite-wait-for-done
PASS: This is my first unit test.
All 1 tests passed.
unittest-suite-success
失敗する場合は次のような感じに表示される.
$ dart --checked test/hello_test.dart
unittest-suite-wait-for-done
FAIL: This is my first unit test.
Expected: 'Hello, Unit Test'
Actual: 'Bye, Unit Test'
Which: is different.
Expected: Hello, Uni ...
Actual: Bye, Unit ...
^
Differ at offset 0
...