5

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();
}
adrian.riobo
  • 495
  • 5
  • 11
  • Which line is line 66? – Duncan Jones Jan 29 '14 at 08:27
  • public static String getDirectoryFromContext(Property jndiName) – adrian.riobo Jan 29 '14 at 08:27
  • 1
    Although I do not know JMockit, the problem seems very clear to me. The error message "Illegal static declaration" tells you everything. The "static" is wrong. Also the example that you linked does not use a static method at this place. How did you come to believe, static must be placed there? (Confusing ...) – Seelenvirtuose Jan 29 '14 at 08:54
  • Ok.. so if this is not the place.. can you tell me how to mock a static method before the class? – adrian.riobo Jan 29 '14 at 08:56

1 Answers1

7

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.

Seelenvirtuose
  • 20,273
  • 6
  • 37
  • 66