[英]Mocking final class with parameterized constructor
I have a final class as below 我的期末课程如下
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? 但这不是嘲笑,我希望有人能帮助我吗?
The method firstclass.firstmethod()
is private method. 方法
firstclass.firstmethod()
是私有方法。 So try to test this method through public method in which it is getting called. 因此,请尝试通过调用该方法的公共方法来测试此方法。
You can mock SecondClass
and its final method using @RunWith(PowerMockRunner.class)
and @PrepareForTest(SecondClass.class)
annotations. 您可以使用
@RunWith(PowerMockRunner.class)
和@PrepareForTest(SecondClass.class)
批注来模拟SecondClass
及其最终方法。
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();
}
}
Libraries used: 使用的库:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.