位置:首页 > Java技术 > Maven在线教程 > 使用Maven运行单元测试

使用Maven运行单元测试

要通过Maven运行单元测试,发出此命令:

mvn test

这会在你的项目中运行整个单元测试。

案例学习

创建两个单元测试,并通过 Maven 的运行它。参见一个简单的 Java 测试类:

package com.yiibai.core;

public class App {
	public static void main(String[] args) {

		System.out.println(getHelloWorld());

	}

	public static String getHelloWorld() {

		return "Hello World";

	}

	public static String getHelloWorld2() {

		return "Hello World 2";

	}
}

Unit Test 1

单元测试为getHelloWorld()方法。

package com.yiibai.core;

import junit.framework.Assert;
import org.junit.Test;

public class TestApp1 {

	@Test
	public void testPrintHelloWorld() {

		Assert.assertEquals(App.getHelloWorld(), "Hello World");

	}

}

Unit Test 2

单元测试为getHelloWorld2()方法。

package com.yiibai.core;

import junit.framework.Assert;
import org.junit.Test;

public class TestApp2 {

	@Test
	public void testPrintHelloWorld2() {

		Assert.assertEquals(App.getHelloWorld2(), "Hello World 2");

	}

}

运行单元测试

使用Maven运行单元测试看见下面的例子。

示例 1
运行整个单元测试(TestApp1和TestApp2),发出以下命令:

mvn test

示例 2
为了运行单个测试(TestApp1),发出此命令:

mvn -Dtest=TestApp1 test [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ yiibai-core --
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ y
ibai-core ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\worksp\yiibai-core\src\test\resou
ces
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ yiibai
core ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ yiibai-core ---
[INFO] Surefire report directory: C:\worksp\yiibai-core\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.yiibai.core.TestApp1
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.143 s
[INFO] Finished at: 2015-11-03T20:29:50+08:00
[INFO] Final Memory: 11M/114M
[INFO] ------------------------------------------------------------------------

示例 3
为了运行单个测试(TestApp2),发出此命令:

mvn -Dtest=TestApp2 test
注意
欲了解更多“mvn test”的例子,请参考Maven测试插件文档