Friday, February 13, 2015

Mockito for Play 2 Framework

Mocking is great! :)
To use Mockito to mock stuff for your tests in Play 2 Framework do the following:

1. Add mockito as dependency in Build.scala:
val appDependencies = Seq(
    ...,
    "org.mockito" % "mockito-all" % "1.10.19"
)
Find latest version from https://github.com/mockito/mockito/blob/master/doc/release-notes/official.md

2. Add imports to your JUnit java file:
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.*;

Note the static import of Mockito. This lets you call mock and when without "Mockito." prefix, like most of the tutorials do.

3. Create mocks:
Either by putting @RunWith(MockitoJUnitRunner.class) on your test class and using @Mock for class members. E.g.:
@RunWith(MockitoJUnitRunner.class)
public class HomeControllerTest {

    @Mock
    HomeForm mockHome;

or by creating the mocks in your code:
HomeForm mockHome = mock(HomeForm.class);

4. Set up mock behavior:
List mockNames = (List) mock(List.class);
when(mockNames.get(0)).thenReturn("bob");
when(mockCompany.getNames()).thenReturn(mockNames);


5. Run using play test, you might want to run play clean first to make sure mockito is downloaded.

Nice feature:
If you've used googlemock - Google C++ Mocking Framework and miss the "Uninteresting function call encountered" messages, for example for debugging, you can get verbose output from mocks by adding withSettings().verboseLogging() like this:
HomeForm mockHome = mock(HomeForm.class, withSettings().verboseLogging());

Sources:
http://www.javacodegeeks.com/2013/05/junit-and-mockito-cooperation.html
http://stackoverflow.com/questions/11802088/how-do-i-enable-mockito-debug-messages
http://www.baeldung.com/mockito-behavior

No comments:

Post a Comment