失敗
給定以下 cmocka 測驗,其中包含依賴項中的靜態變數:
main.c
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include "dependency.h"
void test1(void** state) {
increment();
assert_int_equal(1, get_incrementer());
}
void test2(void** state) {
increment();
assert_int_equal(1, get_incrementer());
}
int main() {
const struct CMUnitTest tests[] = {
cmocka_unit_test(test1),
cmocka_unit_test(test2),
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
dependency.h
void increment();
int get_incrementer();
dependency.c
static int incrementer = 0;
void increment() {
incrementer;
}
int get_incrementer() {
return incrementer;
}
(編譯gcc main.c dependency.c -lcmocka并運行)
我得到以下輸出:
[==========] Running 2 test(s).
[ RUN ] test1
[ OK ] test1
[ RUN ] test2
[ ERROR ] --- 0x1 != 0x2
[ LINE ] --- main.c:14: error: Failure!
[ FAILED ] test2
[==========] 2 test(s) run.
[ PASSED ] 1 test(s).
[ FAILED ] 1 test(s), listed below:
[ FAILED ] test2
1 FAILED TEST(S)
這是因為incrementer不是在每次測驗之間“重置”。
這只是一個證明觀點的最小示例。實際上,我的依賴深入到我在測驗中呼叫的代碼中。
讓它作業的替代方案
但是,如果我將每個測驗分成自己的可執行檔案和自己的測驗組,我就可以incrementer按照預期為每個測驗重新設定。
問題
- 是唯一用 cmocka 實作測驗隔離將每個測驗分離成自己的可執行檔案的嗎?
當我發現這種情況發生時,我很震驚。我是 C 和 C 測驗的新手,我一直認為測驗隔離是單元測驗框架的關鍵部分。對我來說,為什么甚至會有測驗組開始是沒有意義的,因為大多數時候您將測驗具有依賴關系的代碼,其中在某處使用靜態變數,因此每個測驗都會生成一個可執行檔案。
uj5u.com熱心網友回復:
是的,如果您在測驗物件中有一個靜態變數,如果他們期望一個“新鮮”的測驗物件,您需要編譯單獨的測驗。
無論如何,我都會這樣做,每個測驗都在一個單獨的可執行檔案中,因為您的測驗物件中有一個 Singleton。
這是一個很好的例子,為什么單例模式在今天是一種反模式。很難測驗。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/427897.html
