1.按需导入各种jar包
//测试覆盖率
compile group: 'org.jacoco', name: 'jacoco-maven-plugin', version: '0.8.2'
//基本包
testCompile "junit:junit:4.12"
//Spring测试
testCompile group: 'org.springframework', name: 'spring-test', version: '4.3.17.RELEASE'
//mock:,powermock是静态方法的mock
testCompile group: 'org.powermock', name: 'powermock-module-junit4', version: '1.7.4'
testCompile group: 'org.powermock', name: 'powermock-api-mockito', version: '1.7.4'
testCompile group: 'org.mockito', name: 'mockito-all', version: '1.10.19'
//grpc测试
testCompile group: 'io.grpc', name: 'grpc-testing', version: '1.15.0'
2.对JUnit的理解:
JUnit提供了一个很方便的测试环境
建立一个待测试的模版
public int add(int a, int b) {
return a+b;
}
public int addPlus(int a, int b) {
int ans = add(a, b) + 10;
return ans;
}
public int addYou(int a, int b) {
int ans = add(a, b);
ans += YouMath.addLow();
return ans;
}
//测试,加上一个@Test 就可以不需要main方法进行测试
@Test
public void addPlusTest() {
//模拟MyMath方法,架空这个类
MyMath mock = Mockito.mock(MyMath.class);
//模拟MyMath方法,在需要的时候模拟方法
//MyMath spy = Mockito.spy(MyMath.class);
Mockito.doReturn(9).when(mock).add(1, 2);
int ans = mock.addPlus(1, 2);
System.out.println(ans);
}
@Test
public void addYoutest() throws Exception{
MyMath math = new MyMath();
//mock一个静态方法,不需要导入测试环境就可以测试
PowerMockito.mockStatic(YouMath.class);
PowerMockito.doReturn(0).when(YouMath.class, "addLow");
int ans = math.addYou(1, 2);
System.out.println(ans);
}