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!

Comment: rock at Mi, 2 Nov 12:03 PM

simple and nice!

Comment: imom39a at So, 29 Jan 10:41 PM

Thanks for the informative post on Mockito. If you are willing to discuss more on unit testing with mockit and unit testing for other languages can check out Mockito Mock forum which is exclusively for unit testing for different languages. It is a upcoming forum and needs support to make it strong so we can have forum where people can share their knowledge on Testing.

Your comment:

(not displayed)
 
 
 

Live Comment Preview:

 
 
test