gpt4 book ai didi

java - 如何测试实用程序项目的 final方法和静态方法?

转载 作者:IT老高 更新时间:2023-10-28 20:27:50 27 4
gpt4 key购买 nike

我正在尝试为一个项目实现单元测试,它使用一个遗留的“实用程序”项目,其中散布着静态方法,并且许多类是最终的,或者它们的方法是最终的。我根本无法更新旧项目。

JMock 和 EasyMock 都对 final 方法感到窒息,而且我看不到测试静态调用的好方法。有什么技术可以测试这些?

最佳答案

如果您能够重构代码,则可以将您对最终/静态方法的调用包装在简单的实例方法中,例如:

protected Foo doBar(String name) {
return Utility.doBar(name);
}

这允许您在单元测试中覆盖包装器方法以返回 Foo 的模拟实例。

您也可以使用 Powermock ,它扩展了 Easymock(和 Mockito)以允许模拟最终和静态方法:

PowerMock is a framework that extend other mock libraries such as EasyMock with more powerful capabilities. PowerMock uses a custom classloader and bytecode manipulation to enable mocking of static methods, constructors, final classes and methods, private methods, removal of static initializers and more.

这是 example测试模拟一个静态的 final方法,该示例也显示了如何模拟一些其他类型:

@Test
public void testMockStaticFinal() throws Exception {
mockStatic(StaticService.class);
String expected = "Hello altered World";
expect(StaticService.sayFinal("hello")).andReturn("Hello altered World");
replay(StaticService.class);

String actual = StaticService.sayFinal("hello");

verify(StaticService.class);
assertEquals("Expected and actual did not match", expected, actual);

// Singleton still be mocked by now.
try {
StaticService.sayFinal("world");
fail("Should throw AssertionError!");
} catch (AssertionError e) {
assertEquals("\n Unexpected method call sayFinal(\"world\"):",
e.getMessage());
}
}

关于java - 如何测试实用程序项目的 final方法和静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1293337/

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