Tuesday, April 5, 2016

Introduction to testing with Mockito


Mocking helps alleviate the burden of initiliazing and setting up classes prior to the start of a test. While using a mocking framework is not something indispensable, mocking promotes modularity and can make the life of a developer much easier. There are several mocking Java frameworks that can be coupled with a test framework. Some of the well know ones are: Mockito, EasyMock, and JMockit. In this tutorial, we will go through some basic use cases of mocking. We will be using Mockito and JUnit for demonstration purposes.

Mocking objects and method calls


Account account = Mockito.mock(Account.class);

when(account.getUsername()).thenReturn("opencode");
when(account.getPassword()).thenReturn("password1");

//Test successful
assertEquals(account.getUsername(), "opencode");
assertEquals(account.getPassword(), "password1");

//.....

//Lists can be mocked as well using @Mock
@Mock
List<Profile> profileList;

Profile profile1 = Mockito.mock(Profile.class);
Profile profile2 = Mockito.mock(Profile.class);
  
when(profile1.getDescription()).thenReturn("profile1");
when(profile2.getDescription()).thenReturn("profile2");
  
  
when(profileList.get(0)).thenReturn(profile1);
when(profileList.get(1)).thenReturn(profile2);

//Test successful
assertEquals(profileList.get(0).getDescription(), "profile1");
assertEquals(profileList.get(1).getDescription(), "profile2");


Verifying method invocation and the frequency of invocation


//...

System.out.println(account.getUsername());
//verfies that getUsername() is called -- success 
 verify(account).getUsername();

 //verfies that getUsername() is called twice -- failed
 verify(account, times(2)).getUsername();

         

Testing exceptions


//Junit 4.7 or higher
@Rule
public ExpectedException exception = ExpectedException.none();

@Mock
List<Profile> profileList;

when(profileList.get(2)).thenThrow(NullPointerException.class);

//.....
            
 @Test 
public void testException(){
   //result -- success
     exception.expect(NullPointerException.class);
     profileList.get(2);
     }


There are off course more advanced possiblities offered by Mockito, and other frameworks as well.
  

No comments:

Post a Comment