Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to mock object inside of static method?
    primarykey
    data
    text
    <p>I'm trying to mock static method inside of static method.</p> <p>I wonder if it is possible <strong>without using any framework</strong>.</p> <p>Below is what I have tried.</p> <p><strong>Goal:</strong> Mock ImageIO object so that I know what to expect for return value.</p> <pre><code>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; } } </code></pre> <p>I first tried using interface and create a wrapper for ImageIO.</p> <pre><code> 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(); } } </code></pre> <p>And I tried to override static getImageReader() so that I can return MockReader object which then call mock version of read() method:</p> <pre><code>class MockFoo { @Override public static getImageReader() { return MockReader(); } } </code></pre> <p><strong>This is my test code:</strong></p> <pre><code>public void TestRun() { MockFoo foo = new MockFoo(); foo.run(); } </code></pre> <p>Then I figured I can't override static method getImageReader()......</p> <p>Is there a way to achieve my goal?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload