如何使用PowerMock模拟非静态方法 [英] How to mock non static methods using PowerMock
问题描述
我正在尝试模拟测试方法的内部方法
I am trying to mock an inner method call of my test method
我的班级看起来像这样
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中是否有一种模拟行的方法
When I write the junit for the method getStudent(), is there a way in PowerMock to mock the line
dao.getStudentDetails();
或让App类在junit执行期间使用模拟dao对象,而不是连接的实际dao调用
or make the App class use a mock dao object during junit execution instead of the actual dao call which connects to the DB?
推荐答案
您可以使用 whenNew()
方法来自PowerMock(请参阅 https:// github .com / powermock / powermock / wiki / Mockito#how-to-mock-construction-of-new-objects )
You can use the whenNew()
method from PowerMock (see 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类:
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;
}
}
这篇关于如何使用PowerMock模拟非静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!