本文介绍了用参数化构造函数模拟最终类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的最后一堂课如下
public class firstclass{
private String firstmethod(){
return new secondclass("params").somemethod();
}
}
public final class secondclass{
secondclass(String params){
//some code
}
public String somemethod(){
// some code
return somevariable";
}
}
我必须在这里测试头等舱,所以我如下模拟了
I have to here test first class so I have mocked this as below
secondclass classMock = PowerMockito.mock(secondclass .class);
PowerMockito.whenNew(secondclass .class).withAnyArguments().thenReturn(classMock);
Mockito.doReturn("test").when(classMock).somemethod();
但这不是嘲笑,我希望有人能帮助我吗?
But it is not mocking as I expected can anyone help me?
推荐答案
-
方法
firstclass.firstmethod()
是私有方法.因此,请尝试通过调用该方法的公共方法来测试此方法.
The method
firstclass.firstmethod()
is private method. So try to test this method through public method in which it is getting called.
您可以使用@RunWith(PowerMockRunner.class)
和@PrepareForTest(SecondClass.class)
批注模拟SecondClass
及其最终方法.
You can mock SecondClass
and its final method using @RunWith(PowerMockRunner.class)
and @PrepareForTest(SecondClass.class)
annotations.
请在下面查看工作代码:
Please see below the working code:
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(SecondClass.class)
public class FirstClassTest{
@Before
public void init() {
}
@After
public void clear() {
}
@Test
public void testfirstmethod() throws Exception{
SecondClass classMock = PowerMockito.mock(SecondClass.class);
PowerMockito.whenNew(SecondClass.class).withAnyArguments().thenReturn(classMock);
Mockito.doReturn("test").when(classMock).somemethod();
new FirstClass().firstmethod();
}
}
使用的库:
这篇关于用参数化构造函数模拟最终类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!