这个问题指的是在嵌套函数中进行BATS测试,当断言失败时,BATS会在最内层函数中抛出异常,而不是在外层函数中。
为了解决这个问题,我们可以在测试中使用BATS的--no-assert标志来禁用断言,然后手动捕获异常并在需要的位置抛出它。例如:
@test "nested function test" {
run test_function
if [[ $status -ne 0 ]]; then
echo "test_function failed with exit code $status and output" >&2
cat output >&2
exit $status
fi
}
function test_function() {
run another_function
if [[ $status -ne 0 ]]; then
echo "another_function failed with exit code $status and output" >&2
cat output >&2
exit $status
fi
}
function another_function() {
echo "doing something"
assert_equal 1 2
}
在这个例子中,我们在测试中手动运行test_function,再在test_function中手动运行another_function。如果在another_function中的断言失败,我们将手动捕获异常,并在需要的位置抛出它。这可以确保异常被正确地传递到测试框架中,而不是在最内层函数中丢失。