如何编写或模拟 jar 中可用的接口方法?

How to write or mock interface methods available in jar?

有这样的方法

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() 方法我的问题是我如何模拟这个方法我在下面检查 link 但没有帮助

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() 是一些静态调用。在这种情况下,我建议不要使用静态模拟,而是使用包装器和依赖注入。换句话说,首先你创建一个简单的 class...

public class HelperCommandWrapper {
   public Selection getDisplayConfirmation() {
     return XYZ.getHelperCommands().getDisplayConfirmation(timeout);
   }
}

所以,现在您有一个可以模拟的 class(理想情况下,使用接口)。现在,您只需将 class 的实例提供给 class...

的构造函数
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;                                                                               
       }        

瞧,现在您可以轻松地模拟您的特定用例,而不必担心原始实现将调用静态方法。