PowerMockito.whenNew无法正常工作

kau*_*hik 3 java junit powermockito

嗨伙计们我是PowerMockito的新手,我想在PoweMockito中使用whenNew并且它不适合我,有人可以帮我解决这个问题吗?

下面是我用来测试Class2的Test方法,我使用PowerMockito.whenNew来模拟Class2中的mockTestMethod并将String Value作为"MOCKED VALUE"返回但是没有发生,实际上该方法正在执行并输出为"PassedString" ".如果我没有错,那么Output应该将字符串作为"Inside Class2方法MOCKED VALUE",但我得到输出为"Inside Class2方法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;
    }

}
Run Code Online (Sandbox Code Playgroud)

class2在内部调用Class1 mockTestMethod,如上所示.

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();
    }

}
Run Code Online (Sandbox Code Playgroud)

Sil*_*Nak 6

您无法通过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();
    }

}
Run Code Online (Sandbox Code Playgroud)

(我在你的测试类中省略了导入)