(III)Maven - clean compile

在进行完基本的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>
Maven3.3.9的默认构建插件版本信息.jpg

加载了新插件的构建版本信息.png

执行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()方法吧,对应主代码目录生成测试目录结构,如图:

主代码目录结构和测试代码目录结构.png

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实战》学习笔记

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,921评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,635评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,393评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,836评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,833评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,685评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,043评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,694评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,671评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,670评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,779评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,424评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,027评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,984评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,214评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,108评论 2 351
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,517评论 2 343

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,597评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,736评论 6 342
  • 1.编写POM Maven项目的核心文件是pom.xml,POM(Project Objcet Model)项目对...
    zlcook阅读 5,888评论 7 26
  • 简介 概述 Maven 是一个项目管理和整合工具 Maven 为开发者提供了一套完整的构建生命周期框架 Maven...
    闽越布衣阅读 4,272评论 6 39
  • Maven入门教程 1.1.介绍、环境配置 1.1.1.Maven介绍 Maven是一个采用纯Java编写的开源项...
    安易学车阅读 1,452评论 2 10