PowerMockito.whenNew 不工作

PowerMockito.whenNew is not working

大家好,我是 PowerMockito 的新手,我正在尝试在 PoweMockito 中使用 whenNew,但它对我不起作用,有人可以帮我解决这个问题吗??

下面是我用于测试 Class2 的测试方法,我已经使用 PowerMockito.whenNew 在 Class2 中模拟 mockTestMethod 和 return String Value as "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 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();
    }

}

您无法通过 main 方法开始测试 class。相反,对于 JUnit,它应该是 运行。因此,@Test 注释必须出现在测试方法中。 Look here 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();
    }

}

(我在你的测试中遗漏了进口class)