0

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.

HardcoreBro
  • 425
  • 4
  • 17
  • Possible duplicate: http://stackoverflow.com/questions/34571/whats-the-proper-way-to-test-a-class-with-private-methods-using-junit – bobbel Dec 17 '13 at 21:04
  • The difference is that its an enum. I've tried using Whitebox to do it the same way as I would do for a private static method of a class, but I have not had success. – HardcoreBro Dec 17 '13 at 21:07
  • 1
    The point is, that there is not really a difference between calling private static methods in classes or in enums! So, if you found a way of calling private static methods in classes, this should also work for enums. – bobbel Dec 17 '13 at 21:11
  • Duplicate of http://stackoverflow.com/questions/15939023/how-to-mock-an-enum-singleton-class-using-mockito-powermock. See my answer there. – Matt Lachman Dec 18 '13 at 13:36

1 Answers1

1

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

geddamsatish
  • 174
  • 10