我们知道org.mockito.Mockito功能有限,不能mock 私有private、受保护的protected方法
org.powermock.api.mockito.PowerMockito更强大,支持对private和protected和static方法的mock
别忘记,首先要引入maven依赖
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.9</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.9</version>
<scope>test</scope>
</dependency>
一、mock private方法
有如下私有方法需要mock
private MessageBo executeExpression(List<Executor> ruleList, Map<String, Object> replaceMap) {
MessageBo messageBo = new MessageBo();
messageBo.setFlag(Boolean.TRUE);
for (Executor rule : ruleList) {
Bindings bidBindings = getParamValueList(replaceMap, rule.getParam());
Bindings ret = executeExpression(rule.getCompiledScript(), bidBindings);
if (Boolean.FALSE.equals(ret.get("0"))) {
messageBo.setCode((String)ret.get("1"));
messageBo.setMsg((String)ret.get("2"));
messageBo.setFlag(Boolean.FALSE);
break;
}
}
return messageBo;
}
这时候可以利用PowerMockito的spy方法mock出方法所在的对象,然后利用PowerMockito的when(Object instance, String methodName, Object... arguments),调用方法并传递参数,thenAnswer(Answer<?> answer) mock期望的返回结果
具体代码如下:
public class MockTest extends BaseTests {
@Test
public void test() {
GeneralValidateStrategyImpl generalValidateStrategy = PowerMockito.spy(new GeneralValidateStrategyImpl());
List<Executor> ruleList = new ArrayList<>();
Map<String, Object> replaceMap = new HashMap<String, Object>();
try {
PowerMockito.when(generalValidateStrategy,"executeExpression",ruleList, replaceMap).thenAnswer((m) -> {
MessageBo messageBo = new MessageBo();
messageBo.setFlag(Boolean.TRUE);
return messageBo;
});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
二、mock静态方法
如有如下静态方法getCurrentUser文章来源:https://www.toymoban.com/news/detail-523425.html
public class LoginContext {
public static User getCurrentUser() {
LoginContext loginContext = get();
if (loginContext == null) {
return null;
}
return loginContext.getUser();
}
}
mock如下 ,注意需要再测试类加上@PrepareForTest({LoginContext.class}),注解@PrepareForTest里写的类是静态方法所在的类。文章来源地址https://www.toymoban.com/news/detail-523425.html
@PrepareForTest({LoginContext.class})
public class MyUserTest extends BaseTest {
PowerMockito.mockStatic(LoginContext.class);
PowerMockito.when(LoginContext.getCurrentUser()).thenAnswer((m) -> {
User user = new User();
user.setUserName("xxx");
return user;
});
}
到了这里,关于junit单元测试mock私有private方法和静态static方法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!