健兼
powermock对类的静态方法进行mock
jianzhang

特性

首先mockito框架,可以mock,也可以spy,但是不能mock静态方法,和私有方法, 然而powermock支持; mockito中文文档

maven 依赖

1
<properties>
2
<powermock.version>1.7.1</powermock.version>
3
<mockito1.version>1.10.19</mockito1.version>
4
</properties>
5
<dependencies>
6
<!-- 依赖 -->
7
<dependency>
8
<groupId>org.springframework</groupId>
9
<artifactId>spring-test</artifactId>
10
<version>${spring.version}</version>
11
</dependency>
12
<dependency>
13
<groupId>junit</groupId>
14
<artifactId>junit</artifactId>
15
<version>4.12</version>
16
</dependency>
17
<dependency>
18
<groupId>org.mockito</groupId>
19
<artifactId>mockito-core</artifactId>
20
<version>${mockito1.version}</version>
21
<scope>test</scope>
22
</dependency>
23
<dependency>
24
<groupId>org.powermock</groupId>
25
<artifactId>powermock-module-junit4</artifactId>
26
<version>${powermock.version}</version>
27
<scope>test</scope>
28
</dependency>
29
<dependency>
30
<groupId>org.powermock</groupId>
31
<artifactId>powermock-api-mockito</artifactId>
32
<version>${powermock.version}</version>
33
<scope>test</scope>
34
</dependency>
35
<dependency>
36
<groupId>org.powermock</groupId>
37
<artifactId>powermock-module-junit4-rule-agent</artifactId>
38
<version>${powermock.version}</version>
39
<scope>test</scope>
40
</dependency>
41
</dependencies>
42
<build>
43
<!-- 插件配置 -->
44
<plugins>
45
<plugin>
46
<groupId>org.apache.maven.plugins</groupId>
47
<artifactId>maven-surefire-plugin</artifactId>
48
<configuration>
49
<argLine>-javaagent:${settings.localRepository}/org/powermock/powermock-module-javaagent/1.7.1/powermock-module-javaagent-1.7.1.jar -XX:-UseSplitVerifier</argLine>
50
</configuration>
51
</plugin>
52
</plugins>
53
</build>

测试用例

1
@WebAppConfiguration
2
@SpringBootApplication
3
@ContextConfiguration(locations = {"classpath:spring-application.xml"})
4
@RunWith(SpringJUnit4ClassRunner.class)
5
@PrepareForTest(HttpPayUtil.class)//准备静态类
6
public class ControllerTest {
7
8
protected MockMvc mockMvc;
9
10
@Rule
11
public PowerMockRule rule = new PowerMockRule();
12
13
@Autowired
14
protected WebApplicationContext webApplicationContext;
15
16
17
@Before
18
public void setUp() throws Exception {
19
PropertyConfigurator.configure(new FileInputStream(ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX+"log4j.properties")));
20
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
21
}
22
23
/**
24
*
25
* @throws Exception
26
*/
27
@Test
28
public void test()throws Exception{
29
//mock静态类
30
PowerMockito.mockStatic(HttpPayUtil.class);
31
//录制脚本
32
PowerMockito.when(HttpPayUtil.queryOrderDetail("1", PayConstants.PaySource.WEAPP))
33
.thenReturn(new String[]{"2","3"});
34
35
String[] stss = HttpPayUtil.queryOrderDetail("1", PayConstants.PaySource.WEAPP);
36
System.out.println(stss[0]);
37
System.out.println(stss[1]);
38
39
}
40
}

运行测试

Terminal window
1
mvn test
目录