maven安装过程略过。版本3.5.3。
说先使用archetype插件生成项目骨架:
mvn archetype:generate
接着会要求填入一下项目的参数,或者项目坐标
之后就可以看到项目目录了。
pom.xml
src
main
test
这是maven“约定优于配置”的体现,默认地,main目录下是源码,test目录是下是测试,最终打包时,测试部分不会进入包中。
打开pom,看到junit依赖默认是3.8的,这里想要用基于注解的,所以换成4.8。
这是需要执行compile插件,就会重新下载插件,这里很可能会卡住,我们可以切换镜像:
把maven安装目录下的/conf/settings.xml复制到~/.m2目录下,然后配置mirror:
<mirrors>
<!-- mirror
| Specifies a repository mirror site to use instead of a given repository. The repository that
| this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
| for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
|
<mirror>
<id>mirrorId</id>
<mirrorOf>repositoryId</mirrorOf>
<name>Human Readable Name for this Mirror.</name>
<url>http://my.repository.com/repo/path</url>
</mirror>
-->
<mirror>
<id>osc</id>
<mirrorOf>*</mirrorOf>
<url>http://maven.oschina.net/content/groups/public/</url>
</mirror>
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>central</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
</mirrors>
虽然可以直接改maven安装目录下的settings,但是更好的做法是复制一份到用户目录下,这样不会影响到全局,以后maven升级也不用重新配置。
然后重新运行compile,就会子啊~/.m2/repository下看到junit的新版本了。
然后我们可以编写一个方法:
package com.liyao;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
public int add(int a, int b){
return a + b;
}
}
package com.liyao;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class AppTest {
App app;
@Before
public void init(){
app = new App();
}
@Test
public void testAdd(){
Assert.assertEquals(3, app.add(1,2));
}
}
之后运行:mvn clean test
成功。最后可以项目目录下的target目录里看到生成的测试结果。
pom文件:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.liyao</groupId>
<artifactId>helloworld</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>helloworld</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>