Meaningless Drivel is fun!
The moose likes Java in General and the fly likes how to use mockito to mock final classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "how to use mockito to mock final classes" Watch "how to use mockito to mock final classes" New topic

how to use mockito to mock final classes

Nirav Nagda

Joined: Dec 09, 2012
Posts: 5
I am trying MockIto to mock Field class and when I try to do it as below.

I want my program to throw IllegalAccessException so that I can test the library ( that I am testing for my project).

Field mockIT = Mockito.mock(Field.class);
Mockito.doThrow(new IllegalAccessException()).when(mockIT).getInt(String.class);


Exception in thread "main" org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class java.lang.reflect.Field
Mockito cannot mock/spy following:
- final classes
- anonymous classes
- primitive types

does any one know how can I mock the Final class
Janeice DelVecchio
Saloon Keeper

Joined: Sep 14, 2009
Posts: 1789

According to their documentation, Mockito doesn't support mocking a final class. You'll need to choose another mocking framework.

A quick google search says Powermock will do it, but I've not used it so I don't know if it works well/as expected.

Also remember that if you're testing a method as a whole, you might mock out something else inside your try logic that you can make throw the same exception. This will exercise the same catch logic if that's where you're trying to go.

When you do things right, people won't be sure you've done anything at all.
Rob Spoor

Joined: Oct 27, 2005
Posts: 20271

Isn't this the same problem as this thread? If so, please UseOneThreadPerQuestion.

How To Ask Questions How To Answer Questions
dennis deems
Ranch Hand

Joined: Mar 12, 2011
Posts: 808
Make the final class implement an interface, and mock the interface.
Edit: I didn't notice the object you want to mock is from the reflection API. Why on earth do you want to do this?
I agree. Here's the link:
subject: how to use mockito to mock final classes
It's not a secret anymore!