Junit和TestNG都提供了迭代输入参数集合并针对它们运行测试的机制。在 Junit 中,这是通过Parameterized annotation支持的,而 TestNG 使用@DataProvider。
如何使用test-is库编写数据驱动的测试?我尝试使用for列表理解来迭代输入参数集合,但是因为deftest是一个宏,所以它期望是子句。
Junit和TestNG都提供了迭代输入参数集合并针对它们运行测试的机制。在 Junit 中,这是通过Parameterized annotation支持的,而 TestNG 使用@DataProvider。
如何使用test-is库编写数据驱动的测试?我尝试使用for列表理解来迭代输入参数集合,但是因为deftest是一个宏,所以它期望是子句。
从阅读 Junit 中关于参数化测试的文章看来,一旦你通过了扰流板,参数化的酷部分是它可以让你输入以下内容:
return Arrays.asList(new Object[][] {
{ 2, true },
{ 6, false },
{ 19, true },
{ 22, false }
并轻松定义四个测试。
在 test-is 中是等效的(不需要样板代码)宏是are
(are [n prime?] (= prime? (is-prime n))
3 true
8 false)
如果您想将输入作为地图提供,那么您可以运行以下命令:
(dorun (map #(is (= %2 (is-prime %1))
{ 3 true, 8 false}))
尽管are
宏会产生更容易读取的输出。
不确定我是否理解参数化测试的意义,但我会为此使用动态绑定。
user> (def *test-data* [0 1 2 3 4 5])
#'user/*test-data*
user> (deftest foo
(doseq [x *test-data*]
(is (< x 4))))
#'user/foo
user> (run-tests)
Testing user
FAIL in (foo) (NO_SOURCE_FILE:1)
expected: (< x 4)
actual: (not (< 4 4))
FAIL in (foo) (NO_SOURCE_FILE:1)
expected: (< x 4)
actual: (not (< 5 4))
Ran 1 tests containing 6 assertions.
2 failures, 0 errors.
nil
user> (defn run-tests-with-data [data]
(binding [*test-data* data] (run-tests)))
#'user/run-tests-with-data
user> (run-tests-with-data [0 1 2 3])
Testing user
Ran 1 tests containing 4 assertions.
0 failures, 0 errors.
nil
你可以重写deftest
和run-tests
你自己。让测试以其他方式接受参数可能需要十几行 Clojure。