Saturday, December 20, 2014

Introduction

Mocks are simulated objects that can mimic the behaviour of real objects.

We are essentially testing the integration of our code with the database system. This approach of testing is different from unit testing and is called integration testing.
Creating a mocked instance of a class

mockedInstance = PowerMockito.mock(<Class to be mocked>)



Returning dummy data

PowerMockito.when(mockedInstace.methodCall()).thenReturn(<value>);



Verify that a certain method was invoked

Verifications is a process where we assert that a certain method was invoked by the code under test.

PowerMockito.verify(mockedInstance).methodCall()



Verifying that a certain method was never invoked

Mockito.verify(mockedInstance, Mockito.never()).methodCall()



Verifying number of invocations on a static method

PowerMockito.verifyStatic(Mockito.times(1));


Other verification modes 

Mockito.times(int n)
Mockito.atLeastOnce()
Mockito.atLeast(int n)
Mockito.atMost(int n)


InOrder verification

InOrder inOrder = Mockito.inOrder(mockedInstance)

inOrder.verify(mockedInstance).methodOne()
inOrder.verify(mockedInstance).methodTwo()
inOrder.verify(mockedInstance, Mockito.never()).create()



Mocking non-void static methods

@RunWith(PowerMockRunner.class)
@PrepareForTest(Employee.class)
public class EmployeeServiceTest {

    @Test
    public void shouldReturnTheCountOfEmployeesUsingTheDomainClass() {
        PowerMockito.mockStatic(Employee.class);
        PowerMockito.when(Employee.count()).thenReturn(900);

        EmployeeService employeeService = new EmployeeService();
        Assert.assertEquals(900, employeeService.getEmployeeCount());

    }
}

@RunWith(PowerMockRunner.class)
//ask junit to run test with PowerMockRunner

@PrepareForTest({Employee.class})
//Tell PowerMock to prepare the Employee class for tests 
//This is required to mock final classes or classes with final, private, static, or native methods 

PowerMockito.mockStatic(Employee.class)



Mocking a void static method 

    @Test
    public void shouldReturnTrueWhenIncrementOf10PercentageIsGivenSuccessfully() {
        PowerMockito.mockStatic(Employee.class);
        PowerMockito.doNothing().when(Employee.class);
        Employee.giveIncrementOf(10);

        EmployeeService employeeService = new EmployeeService();
        Assert.assertTrue(employeeService.giveIncrementToAllEmployeesOf(10));

    }


Throwing an exception on method call

    @Test
    public void shouldReturnFalseWhenIncrementOf10PercentageIsNotGivenSuccessfully() {
        PowerMockito.mockStatic(Employee.class);
        PowerMockito.doThrow(new IllegalStateException()).when(Employee.class);
        Employee.giveIncrementOf(10);

        EmployeeService employeeService = new EmployeeService();
        Assert.assertFalse(employeeService.giveIncrementToAllEmployeesOf(10));
    }


Mocking a constructor

PowerMockito.whenNew(<Class to mock>).withArguments(<arguments to constructor>).thenReturn(<mockedInstance>)

    @Test
    public void shouldSendWelcomeEmailToNewEmployees() throws Exception {
        Employee employeeMock = PowerMockito.mock(Employee.class);
        PowerMockito.when(employeeMock.isNew()).thenReturn(true);

        PowerMockito.mockStatic(EmployeeIdGenerator.class);

        //Creating the mock for WelcomeEmail.
        WelcomeEmail welcomeEmailMock = PowerMockito.mock(WelcomeEmail.class);

        /**
         *  Notice the whenNew syntax.
         *  PowerMockito.whenNew().withArguments().thenReturn()
         *  informs PowerMock that,
         *  1. When New instance of WelcomeEmail is created,
         *  2. With employee instance and "Welcome to Mocking with PowerMock How-to!" text,
         *  3. Then return a mock of EmployeeEmailService class.
         */
        PowerMockito.whenNew(WelcomeEmail.class)
                .withArguments(employeeMock, "Welcome to Mocking with PowerMock How-to!")
                .thenReturn(welcomeEmailMock);

        EmployeeService employeeService = new EmployeeService();
        employeeService.saveEmployee(employeeMock);

        /**
         * Verifying that the constructor for the WelcomeEmail class is invoked
         * with arguments as the mocked employee instance and text "Welcome to Mocking with PowerMock How-to!".
         */
        PowerMockito
                .verifyNew(WelcomeEmail.class)
                .withArguments(employeeMock, "Welcome to Mocking with PowerMock How-to!");

        //Verifying that the send method was called on the mocked instance.
        Mockito.verify(welcomeEmailMock).send();

    }


Argument Matchers

PowerMockito.when(mockedInstance.methodCall(Mockito.startsWith("deep"))).thenReturn(returnValueOrInstance);


    @Test
    public void shouldFindEmployeeByEmail() {
        final EmployeeService mock = PowerMockito.mock(EmployeeService.class);

        final Employee employee = new Employee();

        //Notice that we are just check if the email address
        //starts with "deep" then we have found the matching employee.
        PowerMockito.when(mock.findEmployeeByEmail(Mockito.startsWith("deep"))).thenReturn(employee);

        final EmployeeController employeeController = new EmployeeController(mock);

        //Following 2 invocations will match return valid employee,
        //since the email address passed does start with "deep"
        Assert.assertSame(employee, employeeController.findEmployeeByEmail("deep@gitshah.com"));
        Assert.assertSame(employee, employeeController.findEmployeeByEmail("deep@packtpub.com"));

        //However, this next invocation would not return a valid employee,
        //since the email address passed does not start with "deep"
        Assert.assertNull(employeeController.findEmployeeByEmail("noreply@packtpub.com"));

    }

Other built-in argument matchers

Mockito.eq
Mockito.matches
Mockito.any
Mockito.isNull
Mockito.isNotNull
Mockito.isA
Mockito.startsWith
Mockito.endsWith


Custom argument matcher

PowerMockito.when(mock.employeeExists(
             Mockito.argThat(new ArgumentMatcher<Employee>()
             {
                  @Override
                  public boolean matches(Object employee)
                  {
                  }
             }
))).thenReturn(true);