Domanda

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();
}
È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top