Searching...
Tuesday, 3 September 2013

Mockito Simple Mocking Example

11:28

In the previous example EasyMock we created Mock object using EasyMock, in this example we will see how to create mock objects in Mockito.

1. Create a Maven project and add below dependency

  <dependency>
	<groupId>org.mockito</groupId>
	<artifactId>mockito-all</artifactId>
	<version>1.8.4</version>
</dependency>

2. Create a POJO class (Employee.java)

package com.pretech;
public class Employee {
	private String name;
	private String address;
	private String age;
//Getters and Setters

3. Create a Java class which needs to be tested

package com.pretech;
public class EmployeeDetails {
	public String createNewEmployee(Employee emp) {
		String result = null;
		if (emp.getAddress().equals("Bangalore")) {
			result = "Employee from bangalore";
		}
		return result;
	}
}

4. Create a Test class using Mockito

package com.pretech;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
public class EmployeeDetailsTest {
	@Mock
	Employee emp;
	@Before
	public void setUp() throws Exception {
		MockitoAnnotations.initMocks(this);
	}
	@Test
	public void test1() {
		String expected = "Employee from bangalore";
		System.out.println("Test1");
		Mockito.when(emp.getAddress()).thenReturn("Bangalore");
		EmployeeDetails stdetails = new EmployeeDetails();
		assertEquals(expected, stdetails.createNewEmployee(emp));
	}
}

5. Run it as JUnit Test cases



image


0 comments: