Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

java - How to mock a static method from JMockit

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() );
} 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To mock your static method:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...