PowerMockito mock static method which throws exception

匿名 (未验证) 提交于 2019-12-03 01:05:01

问题:

I have some static methods to mock using Mockito + PowerMock. Everything was correct until I tried to mock a static method which throws exception only (and do nothing else).

My test class looks like this:

top:

@RunWith(PowerMockRunner.class) @PrepareForTest({Secure.class, User.class, StringUtils.class}) 

body:

    PowerMockito.mockStatic(Secure.class);     Mockito.when(Secure.getCurrentUser()).thenReturn(user);      PowerMockito.mockStatic(StringUtils.class);     Mockito.when(StringUtils.isNullOrEmpty("whatever")).thenReturn(true);      PowerMockito.mockStatic(User.class);     Mockito.when(User.findById(1L)).thenReturn(user); // exception !! ;(      boolean actualResult = service.changePassword(); 

and changePassword method is:

  Long id = Secure.getCurrentUser().id;    boolean is = StringUtils.isNullOrEmpty("whatever");    User user = User.findById(1L);   // ... 

The first 2 static calls works fine (if i comment out 3rd), but the last one ( User.findById(long id) ) throws exception while it is called in 'Mockito.when' method. This method looks like this:

 public static <T extends JPABase> T findById(Object id) {         throw new UnsupportedOperationException("Please annotate your JPA model with @javax.persistence.Entity annotation.");     } 

My question is how can i mock this method to get result as I expect ? Thanks for any help.


EDIT:

Thanks for all replies. I found a solution. I was trying to mock a method findById which was not directly in User.class but in GenericModel.class which User extends. Now everything works perfectly.

回答1:

Try changing this:

PowerMockito.mockStatic(User.class); Mockito.when(User.findById(1L)).thenReturn(user); 

To this:

PowerMockito.mockStatic(User.class); PowerMockito.doReturn(user).when(User.class, "findById", Mockito.eq(1L)); 

See documentation here:



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!