1

変数の値を確認する必要がある単体テストを作成するための同様のコードがあります。

#first.tcl
proc test {a} {
   if {$a < 10} {
      set sig 0
   } else {
      set sig 1
   }
} 
#second.tcl unit testing script
source "first.tcl"
test 10
expect 1 equal to $sig
test 5
expect 0 equal to $sig

最初のスクリプトを変更できないため、変数「sig」の値にアクセスできる方法はありますか。

4

1 に答える 1

3

問題があります。問題は、最初のスクリプトでsigは、への呼び出しが終了すると消えるローカル変数です。test後から調べることはできません。たまたま、 の結果はtestに割り当てられた値sigです。テスト目的でそれを当てにできるかどうかはわかりません。これで十分な場合は、これを行うことができます (Tcl 8.5 を使用していると仮定します。8.4 では、apply用語の代わりにヘルパー プロシージャが必要です)。

source first.tcl
trace add execution test leave {apply {{cmd code result op} {
    # Copy the result of [test] to the global sig variable
    global sig
    set sig $result
}}}

これは (アスペクト指向プログラミングと同様に) の結果をインターセプトし、グローバル変数testに保存します。ただし、テストされたコードの問題に対しては正しくありません。代入は変数への代入であり、その直後に消えます。 sig


多くのテストを行っている場合は、tcltest を使用して作業を行うことを検討してください。これは、Tcl 自体をテストするために使用されるパッケージであり、スクリプトの実行結果のテストを非常に簡単に記述できます。

# Setup of test harness
package require tcltest
source first.tcl

# The tests
tcltest::test test-1.1 {check if larger} -body {
    test 10
} -result 1
tcltest::test test-1.2 {check if smaller} -body {
    test 5
} -result 0

# Produce the final report
tcltest::cleanupTests
于 2012-09-05T08:59:54.727 に答える