Searching...
Wednesday, 28 August 2013

EasyMock Simple Example

11:14

In this example we will see how to write java test cases using EasyMock. This api provides an easy way to create Mock Objects for interfaces and classes generating them on the fly. See more about EasyMock

Software Used

Java 1.7

EasyMock 3.2

Maven

Eclipse Juno

Create a Maven Project and below dependencies

      <dependency>
	<groupId>org.easymock</groupId>
	<artifactId>easymock</artifactId>
	<version>3.2</version>

Create a Simple Java POJO class (Employee.java)

package com.pretech;
public class Employee {
	private String name;
	private String address;
	private String age;
//Generate getters and setters

Create a class to use Employee object

package com.pretech;
public class EmployeeDetails {
	public Employee createNewEmp(Employee emp) {
		System.out.println("Inside create method" + emp.getName());
		return emp;
	}
		
}

Now we are going to test createNewStudent method using EasyMock

package com.pretech;
import static org.junit.Assert.assertEquals;
import org.easymock.EasyMock;
import org.junit.Test;
public class EmployeeDetailsTest {
	
	@Test
	public void testEmployee(){
		//Creating Employee mock object
		Employee employeeMock = EasyMock.createMock(Employee.class);
		//Setting up mock values in this example we are using getName 2 times so it is added .times(2) otherwise second time getName wont work
		EasyMock.expect(employeeMock.getName()).andReturn("Vinod").times(2);
	       //Activating mock
		EasyMock.replay(employeeMock);
	
		//Testing
		EmployeeDetails empetails=new EmployeeDetails();
		Employee emp=new Employee();
		emp=empetails.createNewEmp(employeeMock);
		System.out.println(emp);
		assertEquals("Vinod",emp.getName());
	}
}

Output

Run program as Junit and see below output

image


0 comments: