1、產生的問題:
maven項目執行單元測試可以正常執行,但是執行maven命令test,則報一下異常:
org.apache.maven.plugins:maven-compiler-plugin:2.5.1:testCompile (default-testCompile) on project support: Compilation failure: Compilation failure: [ERROR] E:\workspace\support\src\test\java\com\test\spring\support\TestSpringContextHolder.java:[7,16] 錯誤: 程序包org.junit不存在 [ERROR] E:\workspace\support\src\test\java\com\test\spring\support\TestSpringContextHolder.java:[16,2] 錯誤: 找不到符號 [ERROR] 符號: 類 Test [ERROR] 位置: 類 TestSpringContextHolder [ERROR] E:\workspace\support\src\test\java\com\test\spring\support\TestSpringContextHolder.java:[29,2] 錯誤: 找不到符號 [ERROR] 符號: 類 Before [ERROR] 位置: 類 TestSpringContextHolder [ERROR] E:\workspace\support\src\test\java\com\test\spring\support\TestSpringContextHolder.java:[43,5] 錯誤: 找不到符號
2、產生上述錯誤的原因:
1)、maven項目,單元測試和運行使用不同的classpath,測試使用test-classpath,運行使用classpath;
2)、創建maven項目使用junit默認的版本為3.8.1,它使用的是編程的方式,即使maven dependencies目錄引入了junit,但也無法使用,只能通過build path添加junit支持
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency>
3、解決方案:
將junit的版本提高到4.x,配置代碼如下:
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <!-- 默認的版本為3.8.1,修改為4.x,因為3.x使用的為編程的方式,4.x為注解的形式。 --> <version>4.11</version> <scope>test</scope> </dependency>
4、補充:我上面貼出的異常目錄位於。。。\src\test\java\。。。,不是。。。\src\main\java\。。。,處理方式如上,如果異常發生在main目錄而不是test目錄,同時junit版本是4.x,解決方案則將scope屬性去掉:
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <!-- 默認的版本為3.8.1,修改為4.x,因為3.x使用的為編程的方式,4.x為注解的形式。 --> <version>4.11</version> <!-- 去掉scope作用域,使用默認的compile,編譯、測試、運行都有效的作用域 --> <!--<scope>test</scope>--> </dependency>
解決思路參考:https://blog.csdn.net/javaloveiphone/article/details/52163396