在我們團隊的習慣,會在 Maven 專案裡面使用 Groovy 來寫測試,並且在寫測試時會用 Cucumber 來做整合測試。其中整合測試也許是為了想要跟單元測試分開,所以不會擺在一般 Maven 預設的路徑 src/test 裡面,而是會放在 src/integration-test 裡面,這樣的狀況會導致 IDE 無法正確找到原始碼,Maven 的 dependency 設定也會出現問題。
舉例來說,在我的案例裡,因為 Cucumber 只有測試階段才會使用,因此很自然我會在 Maven 上做這樣的 dependency 設定:
1 2 3 4 5 6 |
< dependency > < groupId >io.cucumber</ groupId > < artifactId >cucumber-java</ artifactId > < version >4.3.1</ version > < scope >test</ scope > </ dependency > |
這邊的 scope 會特地設定成 test,表示 Cucumber 的套件只有在測試期間才會被載入。接著我如果直接上把 src/integration-test/groovy 加入 build path,會因為 Cucumber 只會在測試階段被引用的關係,導致 IDE 發出編譯錯誤的訊息。根本來說,問題是在於我必須要好好地告訴 IDE 或者 Maven 說,src/integration-test/groovy 這個資料夾應該要被視為是測試的資料夾。
所幸,Maven 本身有方法可以自行指定資料夾的功能,也就是利用 build-helper-maven-plugin 這個 plugin。這個 plugin 的功能主要就是讓我們可以告訴 Maven 說哪個資料夾要看成是 source directory、哪個資料夾要看成是 test directory 等等。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
< build > < plugins > < plugin > < groupId >org.codehaus.mojo</ groupId > < artifactId >build-helper-maven-plugin</ artifactId > < version >${maven-build-helper-plugin.version}</ version > < executions > < execution > < id >add-test-sources</ id > < phase >validate</ phase > < goals > < goal >add-test-source</ goal > </ goals > < configuration > < sources > < source >src/test/groovy</ source > < source >src/test/java</ source > < source >src/integration-test/groovy</ source > < source >src/integration-test/java</ source > </ sources > </ configuration > </ execution > < execution > < id >add-test-resources</ id > < phase >generate-test-resources</ phase > < goals > < goal >add-test-resource</ goal > </ goals > < configuration > < resources > < resource > < directory >src/integration-test/resources</ directory > </ resource > </ resources > </ configuration > </ execution > </ executions > </ plugin > </ plugins > </ build > |
可以注意到,在上述的 POM 當中,我設定了 src/integration-test/java 和 src/integration-test/groovy 兩個資料夾都是 test-source 的 source,而 src/integration-test/resources 則是 test-resource 的 resource。如此一來,我就可以在 eclipse 裡面直接依靠 Maven 來幫我設定專案的原始碼資料夾了。
沒有留言:
張貼留言