Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to use mockito to mock final classes

 
Nirav Nagda
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).


//java.lang.reflect.Field
Field mockIT = Mockito.mock(Field.class);
Mockito.doThrow(new IllegalAccessException()).when(mockIT).getInt(String.class);
mockIT.getInt(str);

output:

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
Posts: 1809
12
Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Spoor
Sheriff
Pie
Posts: 20605
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Isn't this the same problem as this thread? If so, please UseOneThreadPerQuestion.
 
dennis deems
Ranch Hand
Posts: 808
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic