Question

Is there a way to invoke a private static method of an enumerated singleton? For example, say I have some legacy code that I need to test which has the following structure:

public enum Singleton {

    INSTANCE;

    private static double methodToTest() {
        return 1.0;
    }       

    public static String extremelyComplexMethod() {
        methodToTest();
        //Imagine lots more complex code here
        return "";
    }
}

How would I go about creating a class that tests methodToTest in isolation? I've tried reflection using Whitebox (included in PowerMock) but I've had no luck. Is there a way to do it?

I know that testing a private method directly is not the prefered method of doing things, but I want to know if its possible to test the private method directly. I tried to get the code to get recognized as java, but I was unsuccessful.

Was it helpful?

Solution

I was able to invoke the method try this following code

@RunWith(PowerMockRunner.class)
@PrepareForTest(Singleton.class)
public class MySingletonTest {   
    @Test
    public void test() throws Exception{ 
        Whitebox.invokeMethod(Singleton.class, "methodToTest");
    }
}

Don't forget to add the Singleton class in PrepareForTest

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top