[英]Mocking final class with parameterized constructor
我的期末課程如下
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";
}
}
我必須在這里測試頭等艙,所以我如下嘲笑了
secondclass classMock = PowerMockito.mock(secondclass .class);
PowerMockito.whenNew(secondclass .class).withAnyArguments().thenReturn(classMock);
Mockito.doReturn("test").when(classMock).somemethod();
但這不是嘲笑,我希望有人能幫助我嗎?
方法firstclass.firstmethod()
是私有方法。 因此,請嘗試通過調用該方法的公共方法來測試此方法。
您可以使用@RunWith(PowerMockRunner.class)
和@PrepareForTest(SecondClass.class)
批注來模擬SecondClass
及其最終方法。
請參見下面的工作代碼:
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();
}
}
使用的庫:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.