如何测试实用程序项目的最终和静态方法? [英] How can I test final and static methods of a utility project?

查看:179
本文介绍了如何测试实用程序项目的最终和静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为aproject实现单元测试,它使用了一个遗留的实用程序项目,这个项目充满了静态方法,许多类都是最终的,或者它们的方法是最终的。我根本无法更新遗留项目。

I'm trying to implement unit testing for aproject, it uses a legacy "utility" project that is littered with static methods and many of the classes are final or their methods are final. I'm not able to update the legacy project at all.

JMock和EasyMock都扼杀了最终方法,我没有看到一种很好的方法来测试静态调用。有哪些技术可以测试这些?

JMock and EasyMock both choke on final methods, and I don't see a nice way to test the static calls. What techniques are there to test these?

推荐答案

如果您能够重构代码,可以将调用包装到简单实例方法中的final / static方法,例如:

If you're able to refactor your code, you can wrap your calls to the final/static methods in simple instance methods, for example:

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

这允许你在单元测试中覆盖你的包装器方法来返回一个模拟Foo的一个例子。

This allows you to override your wrapper method in the unit test to return a mock instance of Foo.

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

Alternatively you can use Powermock, which extends Easymock (and Mockito) to allow mocking of final and static methods:


PowerMock是一个扩展其他方法的框架模拟库,如EasyMock,具有更强大的功能。 PowerMock使用自定义类加载器和字节码操作来模拟静态方法,构造函数,最终类和方法,私有方法,删除静态初始化器等等。

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.

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

Here's an example test mocking a static final method, the example shows how to mock some other types too:

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

这篇关于如何测试实用程序项目的最终和静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆