wood burning stoves 2.0*
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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
Author

how to use mockito to mock final classes

Nirav Nagda
Greenhorn

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).


//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

Joined: Sep 14, 2009
Posts: 1659
    
  11

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
Sheriff

Joined: Oct 27, 2005
Posts: 19651
    
  18

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


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
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: http://aspose.com/file-tools
 
subject: how to use mockito to mock final classes
 
Similar Threads
Mock without interface
PowerMockito + Junit + Ant
What exactly is the point of mock objects (I don't understand them)?
Testing classes that have dependency on third party classes
Generate IllegalAccessException