4

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.

elzix88
  • 63
  • 1
  • 1
  • 5
  • It is not clear if you want to mock an method to throw an exception or you are getting an exception when mocking a method. Furthermore the last bit about JPA doesn't seem to fit in anywhere, or at least it confused me greatly. – Andrew White Mar 20 '13 at 12:47
  • You're already mocking it. So it won't call real method which throws exception – Eugen Martynov Mar 20 '13 at 17:33

1 Answers1

3

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:

Matt Lachman
  • 4,541
  • 3
  • 30
  • 40