在進(jìn)行完基本的POM配置之后质况,我們來(lái)舉個(gè)'小李子'吧
package com.play.myMaven;
/**
* Hello Maven
*
* @author Songyanyan
*/
public class HelloWorld {
public String sayHello(){
return "Hello World";
}
public static void main(String[] args) {
System.out.println(new HelloWorld().sayHello());
}
}
雖然是個(gè)簡(jiǎn)單的‘李子’,我們?nèi)孕枰⒁鈨牲c(diǎn)
- 在絕大多數(shù)情況下玻靡,應(yīng)該把項(xiàng)目主代碼放到src/main/java/目錄下(遵循年Maven的約定)结榄,Maven會(huì)自動(dòng)搜尋該目錄找到項(xiàng)目主代碼
- 一般來(lái)說(shuō),項(xiàng)目中Java類的包都應(yīng)該基于項(xiàng)目的groupId和artifactId囤捻,這樣更加清晰臼朗,同時(shí)也方便搜索構(gòu)件/Java類
清理和編譯
開始編譯咯!
在項(xiàng)目根目錄下運(yùn)行命令mvn clean compile
emmmm蝎土,遺憾的是并沒(méi)有那么順利的像書中那樣一次通過(guò)视哑,發(fā)生了什么呢?(沒(méi)有出現(xiàn)這個(gè)問(wèn)題的小伙伴可以直接跳過(guò)這一部分)
C:\Subversion\MavenPrj\helloMaven>mvn clean complie
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building parent 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.265 s
[INFO] Finished at: 2018-06-05T15:21:33+08:00
[INFO] Final Memory: 6M/123M
[INFO] ------------------------------------------------------------------------
[ERROR] Unknown lifecycle phase "complie". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-i
d>:<plugin-artifact-id>[:<plugin-version>]:<goal>. Available lifecycle phases are: validate, initialize, generate-sources, process-sources, generate-
resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources,
test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install,
deploy, pre-clean, clean, post-clean, pre-site, site, post-site, site-deploy. -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/LifecyclePhaseNotFoundException
第一個(gè)問(wèn)題: 是mvn clean compile !!! 不是complie
修正后誊涯,再次執(zhí)行 mvn clean compile:
C:\Subversion\MavenPrj\helloMaven>mvn clean complie
java.lang.NoClassDefFoundError: Lorg/sonatype/plexus/build/incremental/BuildContext;
at java.lang.Class.getDeclaredFields0(Native Method)
at java.lang.Class.privateGetDeclaredFields(Class.java:2583)
at java.lang.Class.getDeclaredFields(Class.java:1916)
...
Caused by: java.lang.ClassNotFoundException: org.sonatype.plexus.build.incremental.BuildContext
at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50)
at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass(ClassRealm.java:271)
at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:247)
at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:239)
...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.292 s
[INFO] Finished at: 2018-06-05T16:20:13+08:00
[INFO] Final Memory: 7M/123M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.6:resources (default-resources) on project hello-maven: Execution de
fault-resources of goal org.apache.maven.plugins:maven-resources-plugin:2.6:resources failed: A required class was missing while executing org.apache
.maven.plugins:maven-resources-plugin:2.6:resources: Lorg/sonatype/plexus/build/incremental/BuildContext;
又一次的FAILURE挡毅,無(wú)奈,那就用Maven Projects默認(rèn)的Lifecycle中compile直接執(zhí)行暴构,和上面的報(bào)錯(cuò)一致跪呈,百度一圈也沒(méi)找到合適方案,嗯丹壕,那就拆開檢查庆械!
執(zhí)行mvn clean:
C:\Subversion\MavenPrj\helloMaven>mvn clean
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building parent 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ hello-maven ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.175 s
[INFO] Finished at: 2018-06-05T16:28:02+08:00
[INFO] Final Memory: 6M/123M
[INFO] ------------------------------------------------------------------------
這次構(gòu)建成功,那看來(lái)就是complie的問(wèn)題了菌赖,看了下plugins中的版本缭乘,會(huì)不會(huì)是版本問(wèn)題呢?于是看了下最新的Maven plugins信息,更新了一些默認(rèn)構(gòu)建插件:
<build><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</build>
執(zhí)行mvn clean compile:
C:\Subversion\MavenPrj\helloMaven>mvn clean compile
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building parent 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:3.0.0:clean (default-clean) @ hello-maven ---
[INFO] Deleting C:\Subversion\MavenPrj\helloMaven\target
[INFO]
[INFO] --- maven-resources-plugin:3.0.2:resources (default-resources) @ hello-maven ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\Subversion\MavenPrj\helloMaven\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @hello-maven ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 2 source files to C:\Subversion\MavenPrj\helloMaven\target\classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.086 s
[INFO] Finished at: 2018-06-05T16:52:18+08:00
[INFO] Final Memory: 14M/207M
[INFO] ------------------------------------------------------------------------
構(gòu)建成功堕绩!
分析一下log策幼,使用到的構(gòu)建都會(huì)有對(duì)應(yīng)的版本信息輸出:
Scanning for projects :正在掃描
Building parent 1.0-SNAPSHOT :正在構(gòu)建parent 1.0-SNAPSHOT
clean :告訴Maven清理輸出目錄C:\Subversion\MavenPrj\helloMaven\target
-
Using 'UTF-8' encoding to copy filtered resources. :使用“UTF-8”編碼復(fù)制過(guò)濾資源這是在<properties>中添加了
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
可以避免出現(xiàn)警告[WARNING] Using platform encoding (UTF-8 actually) to copy filter
- compile :告訴Maven編譯項(xiàng)目主代碼
執(zhí)行順序:clean:clean任務(wù),刪除target/目錄(默認(rèn)情況下奴紧,Maven構(gòu)建的所有輸出都在target/目錄中)特姐,接著執(zhí)行resources:resources任務(wù)(這里未定義項(xiàng)目資源,暫且略過(guò))黍氮,最后執(zhí)行compiler:compile任務(wù)將項(xiàng)目主代碼編譯至target/classes目錄
上面所提到的clean:clean唐含,resources:resources,compiler:compile
分別對(duì)應(yīng)各插件的不同goal
以上就完成了項(xiàng)目的清理和編譯任務(wù)沫浆,接下來(lái)寫一些單元測(cè)試代碼并讓Maven執(zhí)行自動(dòng)化測(cè)試
自動(dòng)化測(cè)試
主代碼和測(cè)試代碼分別位于獨(dú)立的目錄中捷枯。Maven項(xiàng)目默認(rèn)的主代碼目錄:src/main/java ,默認(rèn)的測(cè)試代碼目錄是src/test/java
先為項(xiàng)目添加一個(gè)JUnit依賴
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
有了groupId:junit专执,artifactId:junit淮捆,version:4.11這三個(gè)值的聲明,就可以確認(rèn)這個(gè)JUnit的坐標(biāo)本股,Maven可以訪問(wèn)中央倉(cāng)庫(kù)并自動(dòng)下載junit-4.11.jar(而在Maven之前我們需要自行去JUnit官網(wǎng)下載分發(fā)包)
scope為依賴范圍攀痊,值為test表示該依賴只對(duì)測(cè)試有效。也就是拄显,測(cè)試代碼中import JUnit是OK的苟径,但是在主代碼中import JUnit會(huì)有編譯錯(cuò)誤。不聲明默認(rèn)值為compile凿叠,表示該依賴對(duì)主代碼和測(cè)試代碼都有效涩笤。
我們來(lái)測(cè)試一下Hello World類的sayHello()方法吧,對(duì)應(yīng)主代碼目錄生成測(cè)試目錄結(jié)構(gòu)盒件,如圖:
package com.play.myMaven;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* HellMavenTest
*
* @author Songyanyan
*/
public class HelloWorldTest {
@Test
public void testSayHello() {
HelloWorld helloWorld = new HelloWorld();
String result = helloWorld.sayHello();
assertEquals("Hello Maven", result);
}
}
典型的單元測(cè)試有三個(gè)步驟:
測(cè)試類及測(cè)試數(shù)據(jù)
測(cè)試的信訪維
-
檢查結(jié)果
調(diào)用Maven執(zhí)行測(cè)試。運(yùn)行mvn clean test
正確結(jié)果如下:C:\Subversion\MavenPrj\helloMaven>mvn clean test [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building parent 1.0-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- maven-clean-plugin:3.0.0:clean (default-clean) @ hello-maven --- [INFO] Deleting C:\Subversion\MavenPrj\helloMaven\target [INFO] [INFO] --- maven-resources-plugin:3.0.2:resources (default-resources) @ hello-maven --- [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] skip non existing resourceDirectory C:\Subversion\MavenPrj\helloMaven\src\main\resources [INFO] [INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @ hello-maven --- [INFO] Changes detected - recompiling the module! [INFO] Compiling 1 source file to C:\Subversion\MavenPrj\helloMaven\target\classes [INFO] [INFO] --- maven-resources-plugin:3.0.2:testResources (default-testResources) @ hello-maven --- [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] skip non existing resourceDirectory C:\Subversion\MavenPrj\helloMaven\src\test\resources [INFO] [INFO] --- maven-compiler-plugin:3.7.0:testCompile (default-testCompile) @ hello-maven --- [INFO] Changes detected - recompiling the module! [INFO] Compiling 1 source file to C:\Subversion\MavenPrj\helloMaven\target\test-classes [INFO] [INFO] --- maven-surefire-plugin:2.20.1:test (default-test) @ hello-maven --- [INFO] [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running com.play.myMaven.HelloWorldTest [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.02 s - in com.play.myMaven.HelloWorldTest [INFO] [INFO] Results: [INFO] [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 1.969 s [INFO] Finished at: 2018-06-05T19:52:48+08:00 [INFO] Final Memory: 16M/167M [INFO] ------------------------------------------------------------------------
可以看到Maven執(zhí)行測(cè)試test之前舱禽,會(huì)先進(jìn)行
- clean:clean
- resources:resources
- compiler:compile
- resources:testResources
- compiler:testCompile
項(xiàng)目主資源處理炒刁、主代碼編譯、測(cè)試資源處理誊稚、測(cè)試代碼編譯等操作翔始,這是Maven生命周期的一個(gè)特性。
通過(guò)編譯的測(cè)試代碼會(huì)在target/test-classes生成二進(jìn)制文件(Compiling 1 source file to C:\Subversion\MavenPrj\helloMaven\target\test-classes)里伯,
然后緊接著surefire:test任務(wù)運(yùn)行測(cè)試(surfire是maven中負(fù)責(zé)測(cè)試的插件)城瞎,運(yùn)行測(cè)試用例,并給出測(cè)試報(bào)告疾瓮,顯然這個(gè)是測(cè)試通過(guò)的例子脖镀,結(jié)果Results:運(yùn)行1條,失敗0條狼电,編譯錯(cuò)誤0條蜒灰,跳過(guò)0條
我們來(lái)看一下測(cè)試失敗的情況:
C:\Subversion\MavenPrj\helloMaven>mvn clean test
...
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.play.myMaven.HelloWorldTest
[ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.025 s <<< FAILURE! - in com.play.myMaven.HelloWorldTest
[ERROR] testSayHello(com.play.myMaven.HelloWorldTest) Time elapsed: 0.006 s <<< FAILURE!
org.junit.ComparisonFailure: expected:<Hello [Maven]> but was:<Hello [World]>
at com.play.myMaven.HelloWorldTest.testSayHello(HelloWorldTest.java:22)
[INFO]
[INFO] Results:
[INFO]
[ERROR] Failures:
[ERROR] HelloWorldTest.testSayHello:22 expected:<Hello [Maven]> but was:<Hello [World]>
[INFO]
[ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.202 s
[INFO] Finished at: 2018-06-05T21:18:19+08:00
[INFO] Final Memory: 16M/163M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.20.1:test (default-test) on project hello-maven: There are test failures.
[ERROR]
[ERROR] Please refer to C:\Subversion\MavenPrj\helloMaven\target\surefire-reports for the individual test results.
[ERROR] Please refer to dump files (if any exist) [date]-jvmRun[N].dump, [date].dumpstream and [date]-jvmRun[N].dumpstream.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
...部分都是一樣的不再贅述
FAILURE! - in com.play.myMaven.HelloWorldTest
在HelloWorldTest類中出現(xiàn)失敗
org.junit.ComparisonFailure: expected:<Hello [Maven]> but was:<Hello [World]> at com.play.myMaven.HelloWorldTest.testSayHello(HelloWorldTest.java:22)
在HelloWorldTest類中22行弦蹂,期望值為<Hello [Maven]>,但是原類值為<Hello [World]>强窖,通過(guò)log輸出可見錯(cuò)誤提示也是很明顯的
注:《Maven實(shí)戰(zhàn)》學(xué)習(xí)筆記