Mock Entity Model class using PowerMockito

77 views
Skip to first unread message

Jimmy Christianto

unread,
Jan 15, 2017, 10:45:08 PM1/15/17
to Play Framework

Hello,

Has anyone tried to mock model class in Java Play Framework 2.3.x? I've tried using PowerMockito but it gave me exception:

 
org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);
Or 'a static method call on a prepared class`
For example:
    @PrepareForTest( { StaticService.class }) 
    TestClass{
       public void testMethod(){
           PowerMockito.mockStatic(StaticService.class);
           when(StaticService.say()).thenReturn(expected);
       }
    }

Also, this error might show up because:
1. inside when() you don't call method on mock but on some other object.
2. inside when() you don't call static method, but class has not been prepared.

Below is my example implementation:

PowerMockito.mockStatic(User.class);
when(User.find.byId(1L)).thenReturn(null);  

Thanks. 

Marcos Pereira

unread,
Jan 17, 2017, 4:08:26 PM1/17/17
to play-fr...@googlegroups.com
Hello Jimmy,

Maybe that is happening because you are mocking User instead of the "find" field inside of User class?

See:

User userMock = mock(User.class)
when(userMock.doSomething()).thenReturn(somethingElse);

The method "doSomething" belongs to "User" class, and then, this will work as expected.

In your case, the method "byId" does not belongs to "User" class. So, what you must do is mock the "find" instance.

Best,

--
You received this message because you are subscribed to the Google Groups "Play Framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to play-framework+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/play-framework/ad17ad86-4847-4c9c-b3b3-7423750ed1b8%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Marcos Pereira
Software Engineer, Lightbend.com

Reply all
Reply to author
Forward
0 new messages