JMockit使用教程
Hz 2020-01-10 Friday
总结一些JMockit的用法
配置
- pom.xml 里添加依赖
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<version>1.48</version>
<scope>test</scope>
</dependency>
1
2
3
4
5
6
2
3
4
5
6
- 添加启动插件
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<jmockit.version>1.48</jmockit.version>
</properties>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version> <!-- or some other version -->
<configuration>
<argLine>
-javaagent:"${settings.localRepository}"/org/jmockit/jmockit/${jmockit.version}/jmockit-${jmockit.version}.jar
</argLine>
</configuration>
</plugin>
</plugins>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
构造方法如何Mock
SimpleBean是一个简单的Bean,Handler里的handler方法new了一个SimpleBean的实例,如何Mock
public class Handler {
public boolean handle() {
SimpleBean simpleBean = new SimpleBean("A");
return "A".equals(simpleBean.getName());
}
}
1
2
3
4
5
6
2
3
4
5
6
方法:
@Test
public void handleMockTest() throws Exception {
// given
new MockUp<SimpleBean>(SimpleBean.class) {
@Mock
void $init(String name) {
}
@Mock
String getName() {
return "B";
}
};
Handler handler = new Handler();
// when
boolean result = handler.handle();
// then
assertFalse("", result);
// 使用tearDown接口清理MockUp
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
附录
参考资料