Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock non static methods using PowerMock

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?

like image 458
Bala Avatar asked Jan 13 '12 03:01

Bala


People also ask

Is PowerMock a mocking framework?

PowerMock is a framework that extends other mock libraries such as EasyMock with more powerful capabilities. PowerMock uses a custom classloader and bytecode manipulation to enable mocking of static methods, constructors, final classes and methods, private methods, removal of static initializers and more.

Can I use Mockito and PowerMock together?

Of course you can – and probably will – use Mockito and PowerMock in the same JUnit test at some point of time.


1 Answers

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;
    }
}
like image 91
Matt Lachman Avatar answered Oct 23 '22 16:10

Matt Lachman