【发布时间】:2018-02-09 17:58:25
【问题描述】:
我有一个班级 RequireJavaVersion,我想为它编写如下所示的测试:
public void execute( EnforcerRuleHelper helper )
throws EnforcerRuleException
{
String javaVersion = SystemUtils.JAVA_VERSION;
Log log = helper.getLog();
log.debug( "Detected Java String: '" + javaVersion + "'" );
javaVersion = normalizeJDKVersion( javaVersion );
此外,我的课程 SystemUtils 看起来像这样:
public static final String JAVA_VERSION = getSystemProperty("java.version");
所以我想写一个这样的测试(使用 JMockit):
@Rule
public ExpectedException exception = ExpectedException.none();
public static class FakeSystemUtils extends MockUp<SystemUtils> {
private final String fakedVersion;
public FakeSystemUtils(String version)
{
this.fakedVersion = version;
}
@Mock
private final String getSystemProperty(final String property) {
return this.fakedVersion;
}
};
..
new FakeSystemUtils( "1.4" );
rule = new RequireJavaVersion();
rule.setVersion( "1.5" );
exception.expect( EnforcerRuleException.class );
exception.expectMessage( "Detected JDK Version: 1.4 is not in the allowed range 1.5." );
rule.execute( helper );
所以目前的问题是 SystemUtils 类似乎被初始化了一次,之后不再初始化......进一步的测试将失败......(或者我弄错了什么)。
所以我现在不确定我是否走错了方向。 Fake 类只会伪造 getProperty..method 但问题是:这是正确的方法还是我需要进入不同的方向并尝试伪造最终的静态属性?有人有想法或提示吗?
【问题讨论】:
-
首先没有
static final String。有一个带有getJavaVersion()方法的类,并传入真实版本或假版本。 -
重点是编写可测试的代码...... ..
-
也许我误解了你的建议,但是 SystemUtils 类是通过
public static final String JAVA_VERSION=..由RequireJavaVersion使用的,除此之外我不想更改该类? -
@Antoniossss 我知道,但这无助于解决问题。在我有机会更改代码之前,我会为现有代码编写测试...
-
我支持“不要为了简单的测试而改变实现”,但其他人可能不同意。如果您不想更改实现,可以使用 PowerMock 的 Whitebox 类将该静态最终字段设置为其他内容。
标签: java unit-testing jmockit