我正在尝试模拟我的测试方法的内部方法调用
我的课看起来像这个
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对象,而不是连接到DB的实际dao调用?
您可以使用PowerMock中的whenNew()
方法(请参阅https://github.com/powermock/powermock/wiki/Mockito#how-模拟新物体的建造)
完整测试用例
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());
}
}
我为这个测试用例制作了一个简单的学生类:
public class Student {
private String name;
public Student() {
name = "real";
}
public String getName() {
return name;
}
}
为了从mocking框架中获得更多,必须注入MyDAO对象。您可以使用类似Spring的Guice,也可以简单地使用工厂模式为您提供DAO对象。然后,在单元测试中,您有一个测试工厂来为您提供模拟DAO对象,而不是真实的对象。然后您可以编写代码,例如:
Mockito.when(mockDao.getStudentDetails()).thenReturn(someValue);
如果您没有访问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
}
}