[英]PowerMockito.whenNew is not working
嗨,大家好,我是PowerMockito的新手,我正在嘗試使用PoweMockito中的whenNew及其不適用於我,有人可以幫我解決這個問題嗎?
下面是我用於測試Class2的Test方法,我已經使用PowerMockito.whenNew在Class2內部模擬了ockTest,並返回了字符串值“ MOCKED VALUE”,但這並沒有發生,實際上該方法正在執行並且輸出是“ PassedString” ”。 如果我沒有記錯的話,輸出應該具有“ Inside Class2 method MOCKED VALUE”的字符串,但我將輸出為“ Inside Class2 method PassedString”。 請提前幫助我,謝謝。
以下是我正在研究的完整程序
package com.hpe.testing2;
public class Class2 {
public void testingMethod(){
Class1 class1 = new Class1();
String result = class1.mockTestMethod("PassedString");
System.out.println("Inside Class2 method " + result);
}
}
package com.hpe.testing2;
public class Class1 {
public String mockTestMethod(String str2){
String str1="SomeString";
str1 = str2;
System.out.println("Inside MockTest Method " + str1);
return str1;
}
}
如上所示,class2在內部調用Class1模擬測試方法。
package com.hpe.testing2;
import org.junit.runner.RunWith;
import org.mockito.Mock;
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({Class2.class,Class1.class})
public class ClassTest {
public static void main(String[] args) throws Exception {
ClassTest testing = new ClassTest();
testing.runMethod();
}
public void runMethod() throws Exception{
Class2 class2 = new Class2();
Class1 class1 = PowerMockito.mock(Class1.class);
PowerMockito.whenNew(Class1.class).withAnyArguments().thenReturn(class1);
PowerMockito.when(class1.mockTestMethod(Mockito.anyString())).thenReturn("MOCKED
VALUE");
class2.testingMethod();
}
}
您不能通過main
方法啟動測試類。 相反,它應該與JUnit一起運行。 因此一個@Test
注釋必須存在在測試方法。 在這里查找 JUnit入門。
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Class2.class, Class1.class })
public class ClassTest {
@Test
public void runMethod() throws Exception {
Class2 class2 = new Class2();
Class1 class1 = PowerMockito.mock(Class1.class);
PowerMockito.whenNew(Class1.class).withAnyArguments().thenReturn(class1);
PowerMockito.when(class1.mockTestMethod(Mockito.anyString())).thenReturn("MOCKED VALUE");
class2.testingMethod();
}
}
(我沒有在您的測試課中導入)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.