0

I have a singleton class that I would like to mock static methods from, so I can test the functionality of the rest of the class. I have created a simpler example to demonstrate. Assume my class that I want to test is this:

public class MockExample {
    
    private static MockExample instance = null;
    private static String ourString = "String from main class";
    
    private MockExample() {
        
    }
    
    public static MockExample getInstance() {
        
        if (instance == null) {
            instance = new MockExample();
        }
        
        return instance;
    }
    
    public String getString() {
        return getClassString();
    }
    
    private static String getClassString() {
        return ourString;
    }

}

I am trying to mock out MockExample.getClassString() call, my replacing the method with PowerMockito inside the test. It is important to note that that method is private and only gets called through getString(). My test code, with my static mock is below:

public class MockExample {
    
    private static MockExample instance = null;
    private static String ourString = "String from main class";
    
    private MockExample() {
        
    }
    
    public static MockExample getInstance() {
        
        if (instance == null) {
            instance = new MockExample();
        }
        
        return instance;
    }
    
    public String getString() {
        return getClassString();
    }
    
    public static String getClassString() {
        return ourString;
    }

}

Online examples suggest that if i get the singleton class after I use PowerMockito.replace(method, stub), than it should call the stub. But in this case it is still calling the original method. I have also tried to "spy", but that is proving to be difficult, since my actual code that I need to mock has arguments. PowerMockito.method() handles those well.

Any help would be greatly appreciated. Thank you.

  • This kind of mock indicates either testing the wrong thing or a seriously compromised design. In this particular case, the fact that `getString()` calls `getClassString()` is _an internal implementation detail_ and should be ignored by the test. Call `getString()` and ensure that it returns the correct value, regardless of how it does so privately. – chrylis -cautiouslyoptimistic- Mar 11 '21 at 20:52
  • https://stackoverflow.com/questions/10583202/powermockito-mock-single-static-method-and-return-object -- Does this answer your question? – Sorin Mar 11 '21 at 20:55
  • This detail is a poor design decision, although the code i'm really implementing has the need for something like this. The code above is just a sample to represent the type of functionality I am actually looking for. You are correct, that I should have written a better example. – javaroolz Mar 11 '21 at 21:25

0 Answers0