今回はこれを使ってシェルスクリプトをテストする方法を紹介します
■環境
CentOS release 5.10 (Final)
bash 3.2.25
shUnit2 2.1.16
bash 3.2.25
shUnit2 2.1.16
■shUnit2のインストール
wget https://shunit2.googlecode.com/files/shunit2-2.1.6.tgz
tar zvxf shunit2-2.1.6.tgz
※ダウンロードして解凍すれば完了です
※テストコードから参照できる場所に配置してください
tar zvxf shunit2-2.1.6.tgz
※ダウンロードして解凍すれば完了です
※テストコードから参照できる場所に配置してください
■サンプルテスト
解凍した「shunit2-2.1.6」と同じ階層にサンプルテスト用のシェルスクリプト(testSample.sh)を作成します
testSample.shの内容は以下の通りです
sh testSample.sh
と実行するとテストが実行されます
[root@localhost work]# ls -ltr 合計 76 drwxr-xr-x 7 1001 users 4096 5月 2 2011 shunit2-2.1.6 -rw-r--r-- 1 root root 61558 5月 2 2011 shunit2-2.1.6.tgz -rw-r--r-- 1 root root 95 5月 29 08:48 testSample.sh
testSample.shの内容は以下の通りです
#! /bin/sh
oneTimeSetUp() {
echo "Start testSample.sh"
}
setUp() {
echo "Start each test method"
}
testSample1() {
assertEquals 1 1
}
testSample2() {
cd /root && ls -ltr 2>&1 > /dev/null
#assertEquals 0 $?
assertEquals "This value is not 0" 0 $?
}
testSample3() {
assertNull "This value is not null" ""
}
testSample4() {
assertTrue "This value is not true" "[ 0 -eq 0 ]"
}
testSample5() {
fail "This test is certainly error !"
}
tearDown() {
echo "End of testSample.sh"
}
# load shunit2
. ./shunit2-2.1.6/src/shunit2
sh testSample.sh
と実行するとテストが実行されます
■Tips
使用できるアサート系一覧
assertHogehogeの第一引数に文字列を追加すると失敗した際にそのメッセージを表示してくれる
わざと失敗に倒す場合は「fail」を使用します
Setup/Teardown メソッドが使えます
「setUp」は各テストが実施される前に実行されます、oneTimeSetUpは事前に1度だけ実施されます
- assertEquals・・・等しい
- assertNotEquals・・・等しくない
- assertSame・・・assertEqualsと一緒
- assertNotSame・・・assertNotEqualsと一緒
- assertNull・・・null(空白文字列)かどうか
- assertNotNull・・・null(空白文字列)かではない
- assertTrue・・・trueかどうか
- assertFalse・・・falseかどうか
assertHogehogeの第一引数に文字列を追加すると失敗した際にそのメッセージを表示してくれる
わざと失敗に倒す場合は「fail」を使用します
Setup/Teardown メソッドが使えます
「setUp」は各テストが実施される前に実行されます、oneTimeSetUpは事前に1度だけ実施されます
■参考サイト















