How to mock a static method from JMockit

Roshanck picture Roshanck · Oct 16, 2014 · Viewed 42.1k times · Source

I have a static method which will be invoking from test method in a class as bellow

public class MyClass
{
   private static boolean mockMethod( String input )
    {
       boolean value;
       //do something to value
       return value; 
    }

    public static boolean methodToTest()
    {
       boolean getVal = mockMethod( "input" );
       //do something to getVal
       return getVal; 
    }
}

I want to write a test case for method methodToTest by mocking mockMethod. Tried as bellow and it doesn't give any output

@Before
public void init()
{
    Mockit.setUpMock( MyClass.class, MyClassMocked.class );
}

public static class MyClassMocked extends MockUp<MyClass>
{
    @Mock
    private static boolean mockMethod( String input )
    {
        return true;
    }
}

@Test
public void testMethodToTest()
{
    assertTrue( ( MyClass.methodToTest() );
} 

Answer

jchen86 picture jchen86 · Oct 21, 2014

To mock your static method:

new MockUp<MyClass>()
{
    @Mock
    boolean mockMethod( String input ) // no access modifier required
    {
        return true; 
    }
};