本文介绍了如何存根 Mockito 测试类的私有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我们有一个名为 SomeClass 的 Java 类
Say we have java class called SomeClass
public class SomeClass {
private boolean isMethod() {
return false;
}
public void sendRequest(String json, String text) {
int messageId;
if (isMethod()) {
messageId = getMessageId(json);
sendMessage(messageId, text);
} else {
throw new IllegalArgumentException();
}
}
private void sendMessage(int messageId, String text) {
}
private int getMessageId(String text) {
Pattern p = Pattern.compile("messageId=(\\d+)&");
Matcher m = p.matcher(text);
if (m.find()) {
return Integer.valueOf(m.group(1));
}
return 0;
}
}
不要在意方法的名字,它们都是可选的.
Don't pay attention to methods' name, they're all optional.
- 我想单独测试
sendRequest(String json, String text)
方法. - 我想存根方法
isMethod()
和getMessageId(json)
,并验证sendMessage(messageId, text)
方法被调用. - 我需要确保
getMessageId(json)
返回 25 并且isMethod()
无论给出哪个参数值都返回 true.
- I want to test
sendRequest(String json, String text)
method in isolation. - I want to stub methods
isMethod()
andgetMessageId(json)
, and verify thatsendMessage(messageId, text)
method is called. - I need to be sure that
getMessageId(json)
returns 25 and thatisMethod()
returns true no matter which argument value given.
推荐答案
这可以通过 PowerMockito 框架来实现.
This could be achieved by PowerMockito framework.
import org.junit.Before;
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(SomeClass.class)
public class SomeClassTest {
private SomeClass someInstance;
@Before
public void setUp() throws Exception {
someInstance = PowerMockito.spy(new SomeClass());
}
@Test
public void sendRequest() throws Exception {
String json = "JSON";
String text = "Some text";
int messageId = 1;
PowerMockito.doReturn(true).when(someInstance, "isMethod");
PowerMockito.doReturn(messageId).when(someInstance, "getMessageId", json);
someInstance.sendRequest(json, text);
PowerMockito.verifyPrivate(someInstance).invoke("isMethod");
PowerMockito.verifyPrivate(someInstance).invoke("getMessageId", json);
PowerMockito.verifyPrivate(someInstance).invoke("sendMessage", messageId, text);
}
}
这篇关于如何存根 Mockito 测试类的私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!