How to mock non static methods using PowerMock

Bala picture Bala · Jan 13, 2012 · Viewed 12.7k times · Source

I am trying to mock an inner method call of my test method

My class looks like this

public class App {
public Student getStudent() {
    MyDAO dao = new MyDAO();
    return dao.getStudentDetails();//getStudentDetails is a public 
                                  //non-static method in the DAO class
}

When I write the junit for the method getStudent(), is there a way in PowerMock to mock the line

dao.getStudentDetails();

or make the App class use a mock dao object during junit execution instead of the actual dao call which connects to the DB?

Answer

Matt Lachman picture Matt Lachman · Jan 3, 2013

You can use the whenNew() method from PowerMock (see https://github.com/powermock/powermock/wiki/Mockito#how-to-mock-construction-of-new-objects)

Full Test Case

import org.junit.*;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.junit.Assert.*;

@RunWith(PowerMockRunner.class)
@PrepareForTest(App.class)
public class AppTest {
    @Test
    public void testGetStudent() throws Exception {
        App app = new App();
        MyDAO mockDao = Mockito.mock(MyDAO.class);
        Student mockStudent = Mockito.mock(Student.class);

        PowerMockito.whenNew(MyDAO.class).withNoArguments().thenReturn(mockDao);
        Mockito.when(mockDao.getStudentDetails()).thenReturn(mockStudent);
        Mockito.when(mockStudent.getName()).thenReturn("mock");

        assertEquals("mock", app.getStudent().getName());
    }
}

I manufactured a simple Student class for this test case:

public class Student {
    private String name;
    public Student() {
        name = "real";
    }
    public String getName() {
        return name;
    }
}