2017-07-26 59 views
1

假設您想對可執行文件中的類執行一些單元測試,但不想將它們重構爲可以使用target_link_libraries(target library)添加該庫的lib在cmake。如何將exe項目鏈接到另一個exe項目中的類

你如何讓測試類訪問其他類?

1)使用其他項目的源文件構建測試項目? 另一件事

include_directories(${otherExeProjectDir}) 

    set(SOURCE_FILES 
    main.cpp 
    tests.h 
    tests.cpp 
    ${otherExeProjectDir}/otherclass1.h 
    ${otherExeProjectDir}/otherclass2.h 
    ) 

2)鏈路測試項目與其他項目OBJ文件? 某種add_library(otherclass.obj)瘋狂?

3)

+0

我不明白你的問題。說你在你的項目中有一門課,現在你想爲這門課做單元測試。你需要做的只是包含該類的頭文件,併爲你的單元測試編寫代碼,併爲你的單元測試編寫一個主函數。 – Yves

+0

兩個項目:其他項目和測試項目。其他項目和測試項目一樣主要。如果我簡單地包含它,測試項目將不知道在哪裏查找標題。 – codeMetis

+0

我不明白。爲什麼你不能包括它。你不能看到它在哪裏嗎? – Yves

回答

2

如果你的主執行程序的源位置是簡單或持平,那麼這樣的事情可以工作:

cmake_minimum_required(VERSION 3.9) 
project(tests) 

# Get main executable source location properties 
get_target_property(exe_sources exe SOURCES) 
get_target_property(exe_source_dir exe SOURCE_DIR) 

# Remove main entry point file 
list(REMOVE_ITEM exe_sources main.cpp) 

# Add test sources 
add_executable(test1 test1.cpp) 

# Add exe sources to test (assumes sources are relative paths) 
foreach(src IN LISTS exe_sources) 
    target_sources(test1 PRIVATE "${exe_source_dir}/${src}") 
endforeach() 

# Add exe include directories to test 
target_include_directories(test1 PRIVATE 
    ${exe_source_dir} 
    $<TARGET_PROPERTY:exe,INCLUDE_DIRECTORIES>) 

否則,一般的解決方案是,不幸的是,依靠一些外部信息,例如頂級源文件位置或將您自己的源屬性添加到主要可執行目標。