本文介绍了如何使用 JUnit、EasyMock 或 PowerMock 模拟静态最终变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想模拟一个静态最终变量以及使用 JUnit、EasyMock 或 PowerMock 模拟一个 i18n 类.我该怎么做?

I want to mock a static final variable as well as mock a i18n class using JUnit, EasyMock or PowerMock. How do I do that?

推荐答案

有没有类似 mocking 变量的东西?我会称之为重新分配.我不认为 EasyMock 或 PowerMock 会给你一个简单的方法来重新分配一个 static final 字段(这听起来像是一个奇怪的用例).

Is there something like mocking a variable? I would call that re-assign. I don't think EasyMock or PowerMock will give you an easy way to re-assign a static final field (it sounds like a strange use-case).

如果你想这样做,你的设计可能有问题:避免 static final(或更常见的全局常量),如果你知道一个变量可能有另一个值,即使是为了测试目的.

If you want to do that there probably is something wrong with your design: avoid static final (or more commonly global constants) if you know a variable may have another value, even for test purpose.

无论如何,您可以使用反射(来自:使用反射更改静态最终 File.separatorChar 进行单元测试?):

Anyways, you can achieve that using reflection (from: Using reflection to change static final File.separatorChar for unit testing?):

static void setFinalStatic(Field field, Object newValue) throws Exception {
    field.setAccessible(true);

    // remove final modifier from field
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

    field.set(null, newValue);
}

使用方法如下:

setFinalStatic(MyClass.class.getField("myField"), "newValue"); // For a String

拆卸时不要忘记将字段重置为其原始值.

Don't forget to reset the field to its original value when tearing down.

这篇关于如何使用 JUnit、EasyMock 或 PowerMock 模拟静态最终变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-26 12:49