问题描述
有类似的方法
public boolean getConfirmation(int timeout) {
Selection Selection;
try {
Selection = XYZ.getHelperCommands().getdisplayConfirmation(timeout);
} catch (Exception e) {
return false;
}
boolean result=false;
if(Selection!=null) {
result= (Selection.compareto(Selection.YES) == 0);
}
logger.info("getConfirmation() completed with result : " + result);
return result ;
}
在上面的方法 helperCommands 是我的 Jar 文件中的一个接口,它包含 getdisplayConfirmation() 方法我的问题是我如何模拟这个方法我在下面的链接中检查但没有帮助
Unit testing of Jar methods in java 我正在使用以下依赖项
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit.vintage.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.0.0</version>
</dependency>
是否必须使用 powermockrunner ?或者上面的代码足以写junit?
解决方法
我假设 XYZgetHelperCommands() 是一些静态调用。在这种情况下,我建议不要使用静态模拟,而是使用包装器和依赖注入。换句话说,首先你创建一个简单的类...
public class HelperCommandWrapper {
public Selection getDisplayConfirmation() {
return XYZ.getHelperCommands().getDisplayConfirmation(timeout);
}
}
所以,现在您有一个可以模拟的类(理想情况下,使用接口)。现在您只需将该类的一个实例添加到您的类的构造函数中...
public WhateverYourClassNameIs(HelperCommandWrapper helperCommandWrapper) {
this.helperCommandWrapper = helperCommandWrapper;
}
...现在您可以在代码中使用它并轻松模拟它...
public boolean getConfirmation(int timeout) {
Selection Selection;
try {
Selection = this.helperCommandWrapper.getDisplayConfirmation(timeout);
} catch (Exception e) {
return false;
}
瞧,现在您可以轻松模拟您的特定用例,而无需关心原始实现是否会调用静态方法。