Ruby 2.1.0 リファレンスマニュアル > ライブラリ一覧 > test/unitライブラリ
ユニットテストを行うためのライブラリです。
このライブラリは 2.2.0 からbundled gem(gemファイルのみを同梱)になりました。詳しい内容は下記のプロジェクトページを参照してください。
なお、2.2.0より前のtest/unit は当時バンドルしていた minitest/unit を使って再実装していましたが、上記のtest/unitと完全な互換性がある訳ではありません。
Rubyのテスティングフレームワークの歴史については以下が詳しくまとまっています。
Test::Unit は以下のように使います。
まずテスト対象のソース(foo.rb)が必要です。
class Foo def foo "foo" end def bar "foo" end end
次にユニットテスト(test_foo.rb)を書きます。テストを実行するメソッド(テストメソッド)の名前は全て test_ で始まる必要があります。テストメソッドが実行される前には setup メソッドが必ず呼ばれます。実行されたあとには、teardown メソッドが必ず呼ばれます。
require 'test/unit' require 'foo' class TC_Foo < Test::Unit::TestCase def setup @obj = Foo.new end # def teardown # end def test_foo assert_equal("foo", @obj.foo) end def test_bar assert_equal("bar", @obj.bar) end end
テストを実行するには上で用意した test_foo.rb を実行します。デフォルトではすべてのテストが実行されます。
$ ruby test_foo.rb Loaded suite test_foo Started F. Finished in 0.022223 seconds. 1) Failure: test_bar(TC_Foo) [test_foo.rb:16]: <"bar"> expected but was <"foo">. 2 tests, 2 assertions, 1 failures, 0 errors, 0 skips
test_bar だけテストしたい場合は以下のようなオプションを与えます。
$ ruby test_foo.rb --name test_bar Loaded suite test_foo Started F Finished in 0.019573 seconds. 1) Failure: test_bar(TC_Foo) [test_foo.rb:16]: <"bar"> expected but was <"foo">. 1 tests, 1 assertions, 1 failures, 0 errors, 0 skips
--name=test_barのような指定は行えません。
以下のようにすると help も表示されます。
$ ruby test_foo.rb --help Usage: test_foo [options] minitest options: -h, --help Display this help. -s, --seed SEED Sets random seed -v, --verbose Verbose. Show progress processing files. -n, --name PATTERN Filter test names on pattern. --jobs-status [TYPE] Show status of jobs every file; Disabled when --jobs isn't specified. -j, --jobs N Allow run tests with N jobs at once --no-retry Don't retry running testcase when --jobs specified --ruby VAL Path to ruby; It'll have used at -j option -q, --hide-skip Hide skipped tests -b, --basedir=DIR Base directory of test suites. -x, --exclude PATTERN Exclude test files on pattern. -Idirectory Add library load path --[no-]gc-stress Set GC.stress as true
複数のテストを一度に行う場合、以下のように書いただけのファイルを実行します。
require 'test/unit' require 'test_foo.rb' require 'test_bar.rb'
上の例では、テストクラスを「定義しただけ」で、テストが実行されています。これは、require 'test/unit'した時にMiniTest::Unit.autorunを実行しているためです。その結果、終了時の後処理として実行されるようになっています。
テストメソッド実行中に例外が発生した。
アサーションに失敗した。
1.9.3 から単体テストの高速化のために、並列実行がサポートされました。
並列化の仕組みについては以下の記事をご覧ください。
Test::Unit | ユニットテストを行うためのモジュールです。 |
test/unit/testcase | (uninitialized) |