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() ); }
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.
Since static method belongs to the class, there is no way in Mockito to mock static methods.
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.
To mock your static method:
new MockUp<MyClass>() { @Mock boolean mockMethod( String input ) // no access modifier required { return true; } };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With