gpt4 book ai didi

java - 用 junit 模拟最后一个类失败

转载 作者:行者123 更新时间:2023-12-01 17:54:56 24 4
gpt4 key购买 nike

我正在尝试使用 Powermock 为以下场景编写 junit。我尝试编写示例代码,而不是复制不允许在此处发布的确切代码。

 class MainClass{
First.getC().setStr("abc");
}

final class First{
public static ClassC getC() {
return c;
}
}

class ClassC{
private String str;
//getter/setter for str
}

它总是失败。我的junit如下:

@RunWith(SpringJUnit4ClassRunner.class)
public class MainClassTest {
@Spy MainClass;

@Mock
private ClassC classc;

@Before
public void setup() {
MockitoAnnotations.initMocks(this);
PowerMockito.mockStatic(First.class);
}
@Test
public void myTest(){
when(First.getC()).thenReturn(classc);
Mockito.doCallRealMethod().when(classc).setStr(Mockito.any(String.class))
}
}

最佳答案

有一个detailed explanations关于模拟静态方法所需的步骤。

你错过了关键

Use the @PrepareForTest(ClassThatContainsStaticMethod.class) annotation at the class-level of the test case.

除此之外:我认为它仍然行不通,因为第一步说:

Use the @RunWith(PowerMockRunner.class) annotation at the class-level of the test case.

这会阻止您使用 Spring 运行程序。

所以,我的建议是:忘记在测试用例中使用需要模拟的静态方法。请记住,无论如何,静态在良好的 OOP 中都是一种异常现象。因此,不是在静态方法中“修复”行为,而是在接口(interface)中表示功能。最坏的情况下,您仍然可以在某个具有静态“单例”实例的类中实现接口(interface),然后将其传递给需要使用该接口(interface)的代码。

因为这样你就可以使用普通的 Mockito 来模拟该接口(interface)并传递模拟!

长话短说:您编写了难以测试的代码,迫使您考虑 PowerMock - 这将迫使您放弃 Spring 测试运行器 - 这将使您的生活变得更加困难 10 倍。因此,将您的代码更改为易于测试并忘记 PowerMock。

关于java - 用 junit 模拟最后一个类失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45868542/

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