April 11, 2010

Mockito Example

« SSH Port Forwading and Tunneling | Main | Java Object Mapping - Dozer Example »

Mockito compared to EasyMock seems to be more easily and has more flexibility. First it's able to mock up interfaces as well as classes. You doesn't need additional Jar libraries. Furthermore there isn't any replay mode. First you have to stub and afterwards you have to verificate your mocked classes or interfaces. Further examples and advantages could be read here. Have a look at the following example:


1. Add the Mockito dependency to your pom.xml:


    org.mockito
    mockito-all
    1.8.4
    test

2. Mockito in JUnit test:

@Test
import static org.mockito.Mockito.*;
//...
@Test
public void testMockito() {
    Map mapMock = mock(Map.class);

    when(mapMock.get("firstKey")).thenReturn("firstValue");
    when(mapMock.get("secondKey")).thenReturn("secondValue");

    Object o = new Object();
    mapMock.put("anyObject", o);

    assertEquals("firstValue", mapMock.get("firstKey"));
    assertEquals("secondValue", mapMock.get("secondKey"));

    verify(mapMock).get("firstKey");
    verify(mapMock).get("secondKey");

    verify(mapMock).put("anyObject", o);
}

Regards
Rafael Sobek

Technorati Tags:

Posted by rafael.sobek at 5:04 PM in Testing

 

[Trackback URL for this entry]

Pingback: links for 2010-04-13 « Java Asgaya at Di, 13 Apr 11:00 AM

Mockito Example
Mockito Example (tags: mockito

Comment: Loic at Di, 27 Jul 9:42 PM

Nice example, thanks!

Your comment:

(not displayed)
 
 
 

Live Comment Preview:

 
« April »
SunMonTueWedThuFriSat
    123
45678910
11121314151617
18192021222324
252627282930