PowerMockito mock static method which throws exception

12,977

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:

Share:
12,977
elzix88
Author by

elzix88

Updated on June 04, 2022

Comments

  • elzix88
    elzix88 almost 2 years

    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.