单元测试模板

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mkcjito.InjectMocks;
import org.mkcjito.Mock;
import org.mkcjito.Mockito;
import org.mkcjito.MockitoAnnotations;

public class Test {
	// 模拟对象
	@Mock
	private ClassA a;
	
	// 被测类
	@InjectMocks
	private Instance instance;
	
	// 初始化
	@BeforeClass
	public static void setUpClass() {
	}
	
	@AfterClass
	public static void tearDownClass() {
	}
	
	@Before
	public void setUp() throws Exception() {
		// 初始化测试用例类中由Mockito的注解标注的所有模拟对象
		MockitoAnnotations.initMocks(this);
	}
	
	@After
	public void tearDown() {
	}
	
	// 辅助方法
	
	// 测试开始!
	public void test01() {
		Assert.assertNull(null);
	}

}

期待抛出异常:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class Test {
	@Rule
	public final ExpectedException exception = ExpectedException.none();

	@Test
	public void test01() {
		exception.expect(SomeException.class);
		instance.function();
	}
}

静态方法Mock

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStaticMethod.class)
public class TestClass {
    @Test
    public void testStaticMethod() {
        PowerMockito.mockStatic(ClassWithStaticMethod.class);
		PowerMockito.when(ClassWithStaticMethod.StaticMethod("param").thenReturn("result");
    }
}