一直没有写单元测试的习惯,导致bug频现,以后代码中必须写单元测试代码,这里记录下maven结合junit运行单元测试方法。
添加配置
工程中添加junit依赖:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
添加maven-surefire-plugin
plugin
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
<configuration>
<includes>
<include>**/*Test.java</include>
</includes>
</configuration>
</plugin>
测试示例
代码
新建AppTest.java
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest extends TestCase {
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest(String testName) {
super(testName);
}
/**
* @return the suite of tests being tested
*/
public static Test suite() {
return new TestSuite(AppTest.class);
}
/**
* Rigourous Test :-)
*/
public void testApp() {
assertTrue(true);
assertEquals("hello", "hello");
}
}
执行测试
执行所有测试
mvn clean test
执行TestClassName测试类的testMethod测试方法
mvn clean test -Dtest=TestClassName#testMethod