Searching...
Sunday, 20 October 2013

How to Mock new instances using PowerMockito

08:54

In the previous example (Mocking Static methods) we created mock values for Static methods, in this example we will see how to mock new instances which are inside methods and there is no public method to set values.

Let us consider below EmployeeDetails class, in this example connection new instance is creating inside createConnection method, during testing we do not want to create a real Connection object for testing. PowerMockito provides PowerMockito.whenNew(..) method to set mock objects when new objects are creating inside the main class.

EmployeeDetails.java

package com.pretech;
public class EmployeeDetails {
	public boolean createConnection() {
		Connection con = new Connection();
		con.connectToDb();
		System.out.println("Connected to Employee Table");
		return true;
	}
}

Connection.java

package com.pretech;
public class Connection {
	public void connectToDb() {
		System.out.println("Creating Database connection");
	}
}

EmployeeDetailsTest.java

package com.pretech;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.legacy.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({EmployeeDetails.class})
public class EmployeeDetailsTest {
	
	@Mock
         Connection connection;
	@Test
	public void testcreateConnection() throws Exception {
	PowerMockito.whenNew(Connection.class).withNoArguments().thenReturn(connection);
         EmployeeDetails empDetails=new EmployeeDetails();
         Assert.assertTrue(empDetails.createConnection());
	}
}


Notes :PowerMock requires below annotations inside test classes

@RunWith(PowerMockRunner.class)
@PrepareForTest({EmployeeDetails.class})

Output



image

0 comments: