在进行完基本的POM配置之后,我们来举个'小李子'吧
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());
}
}
虽然是个简单的‘李子’,我们仍需要注意两点
- 在绝大多数情况下,应该把项目主代码放到src/main/java/目录下(遵循年Maven的约定),Maven会自动搜寻该目录找到项目主代码
- 一般来说,项目中Java类的包都应该基于项目的groupId和artifactId,这样更加清晰,同时也方便搜索构件/Java类
清理和编译
开始编译咯!
在项目根目录下运行命令mvn clean compile
emmmm,遗憾的是并没有那么顺利的像书中那样一次通过,发生了什么呢?(没有出现这个问题的小伙伴可以直接跳过这一部分)
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
第一个问题: 是mvn clean compile !!! 不是complie
修正后,再次执行 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,无奈,那就用Maven Projects默认的Lifecycle中compile直接执行,和上面的报错一致,百度一圈也没找到合适方案,嗯,那就拆开检查!
执行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] ------------------------------------------------------------------------
这次构建成功,那看来就是complie的问题了,看了下plugins中的版本,会不会是版本问题呢?于是看了下最新的Maven plugins信息,更新了一些默认构建插件:
<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>
执行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] ------------------------------------------------------------------------
构建成功!
分析一下log,使用到的构建都会有对应的版本信息输出:
Scanning for projects :正在扫描
Building parent 1.0-SNAPSHOT :正在构建parent 1.0-SNAPSHOT
clean :告诉Maven清理输出目录C:\Subversion\MavenPrj\helloMaven\target
-
Using 'UTF-8' encoding to copy filtered resources. :使用“UTF-8”编码复制过滤资源这是在<properties>中添加了
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
可以避免出现警告[WARNING] Using platform encoding (UTF-8 actually) to copy filter
- compile :告诉Maven编译项目主代码
执行顺序:clean:clean任务,删除target/目录(默认情况下,Maven构建的所有输出都在target/目录中),接着执行resources:resources任务(这里未定义项目资源,暂且略过),最后执行compiler:compile任务将项目主代码编译至target/classes目录
上面所提到的clean:clean,resources:resources,compiler:compile
分别对应各插件的不同goal
以上就完成了项目的清理和编译任务,接下来写一些单元测试代码并让Maven执行自动化测试
自动化测试
主代码和测试代码分别位于独立的目录中。Maven项目默认的主代码目录:src/main/java ,默认的测试代码目录是src/test/java
先为项目添加一个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这三个值的声明,就可以确认这个JUnit的坐标,Maven可以访问中央仓库并自动下载junit-4.11.jar(而在Maven之前我们需要自行去JUnit官网下载分发包)
scope为依赖范围,值为test表示该依赖只对测试有效。也就是,测试代码中import JUnit是OK的,但是在主代码中import JUnit会有编译错误。不声明默认值为compile,表示该依赖对主代码和测试代码都有效。
我们来测试一下Hello World类的sayHello()方法吧,对应主代码目录生成测试目录结构,如图:
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);
}
}
典型的单元测试有三个步骤:
测试类及测试数据
测试的信访维
-
检查结果
调用Maven执行测试。运行mvn clean test
正确结果如下: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执行测试test之前,会先进行
- clean:clean
- resources:resources
- compiler:compile
- resources:testResources
- compiler:testCompile
项目主资源处理、主代码编译、测试资源处理、测试代码编译等操作,这是Maven生命周期的一个特性。
通过编译的测试代码会在target/test-classes生成二进制文件(Compiling 1 source file to C:\Subversion\MavenPrj\helloMaven\target\test-classes),
然后紧接着surefire:test任务运行测试(surfire是maven中负责测试的插件),运行测试用例,并给出测试报告,显然这个是测试通过的例子,结果Results:运行1条,失败0条,编译错误0条,跳过0条
我们来看一下测试失败的情况:
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类中出现失败
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]>,通过log输出可见错误提示也是很明显的
注:《Maven实战》学习笔记