7

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

我的课看起来像这样

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 执行期间使用模拟 dao 对象,而不是连接到数据库的实际 dao 调用?

4

3 回答 3

13

您可以使用whenNew()PowerMock 中的方法(请参阅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;
    }
}
于 2013-01-03T13:47:08.403 回答
1

为了充分利用模拟框架,必须注入 MyDAO 对象。您可以使用 Spring our Guice 之类的东西,也可以简单地使用工厂模式为您提供 DAO 对象。然后,在您的单元测试中,您有一个测试工厂来为您提供模拟 DAO 对象而不是真实对象。然后你可以编写如下代码:

Mockito.when(mockDao.getStudentDetails()).thenReturn(someValue);
于 2012-01-13T16:45:07.107 回答
-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
    }
}
于 2013-04-22T17:57:44.270 回答