PowerMockito mock static method which throws excep

2019-07-20 04:44发布

问题:

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:

  • PowerMockitoStubber javadoc
  • PowerMockito Usage