Why does Missing Method Invocation Exception occur when mocking org apache log4j Level in Mockito?

When attempting to mock a Level class from org.apache.log4j using Mockito, the test throws a MissingMethodInvocationException. For example, using when(level.getSyslogEquivalent()).thenThrow(ioException); results in this error. What causes this exception, and how can it be resolved when mocking classes like Level

I ran into the same issue. The root cause is that org.apache.log4j.Level is a final class, and by default, Mockito cannot mock final classes or final methods unless configured to do so. That’s why when(level.getSyslogEquivalent()) fails with MissingMethodInvocationException — Mockito never actually intercepted a mock call.

To fix this, you can either:

Enable mock-maker-inline in mockito-extensions/org.mockito.plugins.MockMaker with the content:

mock-maker-inline

This allows Mockito to mock final classes. 2. Or wrap the Level instance in a small wrapper or adapter interface and mock that instead.

Yep, I’ve seen this happen a lot with Log4j’s Level class. Another approach I use is not mocking Level at all, but rather passing in real instances or using predefined constants like Level.INFO. Usually, your code doesn’t need to mock Level itself — just the logger behavior. Mocking final classes can get messy, even with inline mock-maker enabled.

Also, keep in mind that Mockito can mock final classes only in Mockito 2.1+ with the inline mock-maker. If you’re using an older version, you’ll hit MissingMethodInvocationException every time. Alternatively, you could switch to PowerMockito, which can mock final and static methods, but it’s heavier and adds complexity.