要通過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"; } }
單元測試為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"); } }
單元測試為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