gpt4 book ai didi

java - PowerMockito.whenNew 不工作

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:39:53 25 4
gpt4 key购买 nike

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

下面是我用于测试 Class2 的测试方法,我使用 PowerMockito.whenNew 在 Class2 中模拟 mockTestMethod 并将字符串值返回为“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 方法启动测试类。相反,它应该与 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();
}

}

(我在你的测试类中遗漏了导入)

关于java - PowerMockito.whenNew 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43542690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com