Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock a static method from JMockit

Tags:

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() ); }  
like image 426
Roshanck Avatar asked Oct 16 '14 15:10

Roshanck


People also ask

How can we mock static methods?

Mocking a No Argument Static Method 0, we can use the Mockito. mockStatic(Class<T> classToMock) method to mock invocations to static method calls. This method returns a MockedStatic object for our type, which is a scoped mock object.

Can we mock static methods with Mockito?

Since static method belongs to the class, there is no way in Mockito to mock static methods.

How do you mock a private static method?

For Mockito, there is no direct support to mock private and static methods. In order to test private methods, you will need to refactor the code to change the access to protected (or package) and you will have to avoid static/final methods.


1 Answers

To mock your static method:

new MockUp<MyClass>() {     @Mock     boolean mockMethod( String input ) // no access modifier required     {         return true;      } }; 
like image 66
jchen86 Avatar answered Sep 30 '22 20:09

jchen86