如何在静态方法中模拟对象?

时间:2012-12-20 07:54:07

标签: java static mocking

我正在尝试在静态方法中模拟静态方法。

我想知道是否有可能不使用任何框架

以下是我的尝试。

目标:模拟ImageIO对象,以便我知道对返回值的期望。

class Foo {

  public static SomeObject Run(String path) {
     File file = new File(path);
     BufferedImage buff = ImageIO.read(file);

     SomeObject some = new SomeObject(buff);
     return some;
  }
}

我首先尝试使用interface并为ImageIO创建一个包装器。

 interface ImageReader {
     public BufferedImage read(File file);
 }

 class RealReader implements ImageReader {
     @Override
     public BufferedImage read(File file) {
         return ImageIO.read(file);
     }
 }

 class MockReader implements ImageReader {
     @Override
     public BufferedImage read(File file) {
         BufferedImage buff = new BufferedImage(0,0,0);
         //do whatever I like here and return the buff
         return buff;
     }
 }


 class Foo {

      public static SomeObject run(String path) {
         File file = new File(path);

         //ImageIO wrapper             
         ImageReader reader = getImageReader();
         BufferedImage buff = reader.read(file);


         SomeObject some = new SomeObject(buff);
         return some;
      }

      public static getImageReader() {
         return RealReader();
      }
  }

我试图覆盖静态getImageReader(),以便我可以返回MockReader对象 然后调用read()方法的模拟版本:

class MockFoo {
    @Override
    public static getImageReader() {
        return MockReader();
    }
}

这是我的测试代码:

public void TestRun() {

    MockFoo foo = new MockFoo();
    foo.run();

}

然后我想我无法覆盖静态方法getImageReader()......

有没有办法实现我的目标?

1 个答案:

答案 0 :(得分:3)

一种方法是更改​​run的签名:

public static SomeObject run(ImageReader imageReader, String path) {
    // ...