如何使用PowerMock模拟非静态方法

时间:2012-01-13 03:41:20

标签: powermock non-static

我正在尝试模拟我的测试方法的内部方法调用

我的班级看起来像这样

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

当我为方法getStudent()编写junit时,PowerMock中是否有一种模拟行的方法

dao.getStudentDetails();

或使App类在junit执行期间使用mock dao对象而不是连接到DB的实际dao调用?

3 个答案:

答案 0 :(得分:8)

您可以使用PowerMock中的whenNew()方法(请参阅https://github.com/powermock/powermock/wiki/Mockito#how-to-mock-construction-of-new-objects

完整测试用例

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());
    }
}

我为这个测试用例制作了一个简单的Student类:

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

答案 1 :(得分:1)

为了远离模拟框架,必须注入MyDAO对象。你可以使用Spring我们的Guice之类的东西,或者只是使用工厂模式为你提供DAO对象。然后,在您的单元测试中,您有一个测试工厂为您提供模拟DAO对象而不是真实对象。然后你可以编写如下代码:

Mockito.when(mockDao.getStudentDetails()).thenReturn(someValue);

答案 2 :(得分:-1)

如果您无法访问Mockito,您也可以使用PowerMock来实现相同的目的。例如,您可以执行以下操作:

@RunWith(PowerMockRunner.class)
@PrepareForTest(App.class)
public class AppTest {
    @Test
    public void testGetStudent() throws Exception {
        MyDAO mockDao = createMock(MyDAO.class);
        expect(mockDao.getStudentDetails()).andReturn(new Student());        
        replay(mockDao);        

        PowerMock.expectNew(MyDAO.class).andReturn(mockDao);
        PowerMock.replay(MyDAO.class);         
        // make sure to replay the class you expect to get called

        App app = new App();

        // do whatever tests you need here
    }
}