1 创建一个标准的Maven工程,Pom中切记要选择
2 引入JMockit依赖
junit junit 4.12 org.jmockit jmockit 1.38
3 引入maven-surefire-plugin,否则Jmockit测试跑完后,并不会生成HTML测试覆盖率的报告
maven-compiler-plugin 2.5.1 1.8 maven-surefire-plugin 2.20 html target/coverage-report
这里要特别注意一点,maven test命令只会跑 src/test/java下测试类,命名规则如下:
默认包含的测试类:
**/*Test.java
**/Test*.java
**/*TestCase.java
默认排除的测试类:
**/Abstract*Test.java
**/Abstract*TestCase.java
4 举个列子:
@RunWith(JMockit.class) public class TestJApp1_1 { @Tested Service testedService; @Injectable Dependency dependency; @Test public void exeUnitTest() { new Expectations() {{ dependency.findSomeData(anyString); result = new Data("345"); }}; testedService.doSomething("..."); } }
该测试类放在src/test/java下
public class Service { private Dependency dependency; public Data doSomething(String someData) { Data data = dependency.findSomeData(someData); System.out.println(data.getText()); return data; } public String fun() { return "call original method"; } } public class Dependency { public Data findSomeData(String anyString) { System.out.println("Dependency -->"+anyString); log(anyString); return new Data(anyString); } private void log(String text){ System.out.println("Dependency private log -->"+text); } } public class Data { private String text; public Data(String text) { this.text = text; } public String getText() { return text; } }
这个类放在src/main/java下。右键runas 或者maven test 都会生成测试报告,效果如下