According to the example in the Jmockit tutorial this code should do the trick:
@BeforeClass
public static void setUpClass() {
new MockUp<UtilJndi>(){
@Mock
public static String getDirectoryFromContext(Property jndiName) // line 66
throws DirectoryNotFoundException {
return "noDirectory";
}
};
}
But it shows:
myclass.java:[66,29] error: Illegal static declaration
How can I resolve this?
I will add another workaround wich works for me:
I create my mocked class extending MockUp:
public static class MockUtilJndi extends MockUp<UtilJndi> {
public MockUtilJndi() {
super();
}
@Mock
public static String getDirectoryFromContext(Property jndiName)
throws DirectoryNotFoundException {
return "noDirectory";
}
}
If you notice I call the super() inside my constructor. Cause according to documentation if you call MockUp constructor it will change the implementation in the target class.. so once you have this in your mocked class constructor you just need to create your class inside the @BeforeClass annotated method:
@BeforeClass
public static void setUpClass() {
new MockUtilJndi();
}
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.
If you need to mock a static method, it is a strong indicator for a bad design. Usually, you mock the dependency of your class-under-test. If your class-under-test refers to a static method - like java.
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. Therefore, in our unit test above, the utilities variable represents a mock with a thread-local explicit scope.
Ok, I will update my comment to an answer.
First, the error message is very clear. "Illegal static declaration" just means, that the static keyword is placed wrong. Remove it!
As you are trying to mock a static method, you might have believed that you must put the static keyword also. But the documentation for the Mock annotation says:
Method modifiers (including public, final, and even static), however, don't have to be the same.
That simply means, you can mock static methods even without declaring it static.
Hmm ... I strongly feel, that the documentation's wording is a bit confusing. Obviously, it is not an option, but you must not declare it static.
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