添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
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
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.