1.maven依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.2</version>
<scope>test</scope>
</dependency>
2.方法介绍(junit)
(1)@BeforeClass:静态方法,当前测试类加载前调用;
(2)@AfterClass:静态方法,当前测试类回收前调用;
(3)@Before:每一次执行@Test修饰的测试方法前调用,常用于初始化;
(4)@After:每一次执行完@Test修饰的测试方法后调用;
(5)@Test:测试方法,每一个方法必须要有断言,测试方法之间没有依赖,能否独立执行。
3.测试样例
待测代码:
1 public class Calculator {
2 private int init;
3 public Calculator(int init) {
4 this.init = init;
5 }
6 public int add(int a,int b) {
7 return init+a+b;
8 }
9
10
11 }
测试方法:
1 import org.junit.Before;
2 import org.junit.BeforeClass;
3 import org.junit.Test;
4 import static org.junit.Assert.*;
5
6 public class CalculatorTest {
7 private Calculator calculator;
8 private static int init;
9 @BeforeClass
10 public static void setup() {
11 init = 2;
12 }
13 @Before
14 public void setup_1() {
15 calculator = new Calculator(init);
16 }
17 @Test
18 public void add_返回setup_1函数初始化的值_returnTrue() {
19 assertEquals(6,calculator.add(1,3));
20 }
21
22 @Test
23 public void add_返回setup_1函数初始化的值_returnFalse() {
24 assertFalse(7==calculator.add(1,3));
25 }
26 }
结果:

测试通过。@BeforeClass修饰的方法赋初值,@Before修饰的方法初始化calculator对象,@Test修饰的方法进行测试,简单可知,初始值为2,加上1加上3,结果为6;测试样例1 assertEquals断言满足结果为6,正确;测试样例2 assertFalse 断言结果7与计算结果6比较不相等,为false,预取得的条件是false,测试通过。
4.powermock,对有static、native、private、final方法的类进行模拟。
在测试类前加上:
@RunWith(PowerMockRunner.class) // 告诉JUnit使用PowerMockRunner进行测试
@PrepareForTest({拥有静态方法的类.class}) // 所有需要测试的类列在此处,适用于模拟final类或有final, private, static, native方法的类
@PowerMockIgnore("javax.management.*") //为了解决使用powermock后,提示classloader错误
在调用静态方法之前:
PowerMockito.mockStatic(拥有静态方法的类.class);
when(拥有静态方法的类.静态方法(any(参数1.class),any(参数2.class))).thenReturn("字符串");
然后调用静态方法
拥有静态方法的类.静态方法(参数1,参数2),刚方法返回值为"字符串"。