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