簡體   English   中英

CppUTest單元測試框架多重定義異常

[英]CppUTest Unit Testing Framework Multiple Definition Exception

我將嘗試將此作為一個純粹的最小示例,以盡可能適用於盡可能多的人,並保護可能違反NDA的任何類型的代碼共享。 希望這沒關系!

我正在使用CppUTest和CppUMock(使用CMake編譯gcc / g ++和makefile)與Gitlab Continuous Integration軟件一起為未來的提交和軟件發布創建單元測試環境。 但是,我遇到了一些問題。 假設我有以下文件夾設置(除了/ tests文件夾的內容之外,我具有最小的更改能力):

+-- src
    +-- driver1.c
    +-- driver2.c
+-- inc
    +-- driver1.h
    +-- driver2.h
+-- tests
    +-- test_driver1.cpp
    +-- test_driver2.cpp
    +-- main.cpp
    +-- cmakelists.txt

CMakeLists文件將包含inc文件夾的包含,src文件夾的編譯以及tests文件夾的編譯。 但是,假設driver2.c依賴於driver1.c定義的方法。 如果沒有模擬設置,這很好,因為你可以正常測試對driver2方法的調用結果。 但是,假設我想模擬driver1的method1函數,以便我可以檢查driver2是否正確調用了method1(使用CppUMock)。 如果沒有編譯driver1,那么通常會沒問題,但是在test_driver2.cpp文件中添加類似的內容:

void method1(int n) {
    mock().actualCall("method1").withParameter("n", n);
}

將導致與driver1.c中的實際method1發生沖突,並發生鏈接器錯誤,如下所示:

CMakeFiles/Tests.dir/.../src/driver1.c:(.text+0x11d): multiple definition of 'method1'
CMakeFiles/Tests.dir/.../src/test_driver2.cpp:(.text+0x0): first defined here

根據評論者的要求,包含結構如下:

driver1.c includes driver1.h (obviously)
driver2.c includes driver2.h (obviously)
driver2.h includes driver1.h (for calling method1)
test cpp files include their respective .h files
(test_driver1.cpp -> driver1.h and test_driver2.cpp -> driver2.h)

method1在driver1.h中聲明並在driver1.c中定義。 我無法編輯這些文件。

我很樂意按要求添加詳細信息。

解決這個嘲弄問題的最佳方法是什么?

如果要從driver1.h模擬method1 ,只需將模擬的定義添加到單獨的mock_driver1.cpp中,然后添加到CMakeLists.txt中:

add_executable(target1 test_driver1.cpp driver1.cpp)
add_executable(target2 test_driver2.cpp driver2.cpp mock_driver1.cpp)

完成mock_driver1.cpp ,將mock_driver1.cpp依賴項替換為driver1.cpp

這都假設您為每個測試驅動程序都有一個單獨的可執行文件

但是,如果你想擁有所有驅動程序連接在一起的一個大主要項目,那么你就不能同時擁有真正的method1和嘲笑method1並存在一起。 為此,我建議將mock method1包裝在名稱空間mock或類似的東西中,並且只在test_driver2.cpp中調用mock::test1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM