Keep Traveling

Mockito Simple Mocking Example

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


No comments:

Post a Comment

Featured Post

Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts