Mockito 使用 PowerMock 让 Mockito 支持静态方法
PowerMock 是一个增强库,用来增加 Mockito 、EasyMock 等测试库的功能。
Mockito 默认是不支持静态方法
比如我们在 ExampleService 类中定义静态方法 add:
public class ExampleService { public static int add(int a, int b) { return a+b; } }
尝试给静态方法打桩,会报错:
import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class MockitoDemo { @Test public void test() { // 会报错 when(ExampleService.add(1, 2)).thenReturn(100); } }
可以用 Powermock 弥补 Mockito 缺失的静态方法 mock 功能
在 build.gradle 中配置以下依赖:
dependencies { testCompile group: 'junit', name: 'junit', version: '4.12' testCompile group: 'org.mockito', name: 'mockito-core', version: '2.25.1' // PowerMock 相关依赖 testCompile group: 'org.powermock', name: 'powermock-core', version: '2.0.0' testCompile group: 'org.powermock', name: 'powermock-module-junit4', version: '2.0.0' testCompile group: 'org.powermock', name: 'powermock-api-mockito2', version: '2.0.0' }
示例:
import org.junit.Assert; 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; import static org.mockito.Mockito.*; @RunWith(PowerMockRunner.class) // 这是必须的 @PrepareForTest(ExampleService.class) // 声明要处理 ExampleService public class MockitoDemo { @Test public void test() { PowerMockito.mockStatic(ExampleService.class); // 这也是必须的 when(ExampleService.add(1, 2)).thenReturn(100); Assert.assertEquals(100, ExampleService.add(1, 2)); Assert.assertEquals(0, ExampleService.add(2, 2)); } }
PowerMockRunner 支持 Mockito 的 @Mock 等注解
上面我们用了 PowerMockRunner ,MockitoJUnitRunner 就不能用了。但不要担心, @Mock 等注解还能用。
import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.powermock.modules.junit4.PowerMockRunner; import java.util.Random; import static org.mockito.Mockito.*; @RunWith(PowerMockRunner.class) public class MockitoDemo { @Mock private Random random; @Test public void test() { when(random.nextInt()).thenReturn(1); Assert.assertEquals(1, random.nextInt()); } }
转载:https://www.letianbiji.com/java-mockito/mockito-powermock-static.html