gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:17:33 26 4
gpt4 key购买 nike

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

我的类(class)看起来像这样

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 调用?

最佳答案

您可以使用 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;
}
}

关于powermock - 如何使用 PowerMock 模拟非静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8845621/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com