如何模拟PowerMockito.spy()已监视的另一个类中的成员类?
@Component
public class BoxFileDao {
@Autowired
private BoxFileService boxFileService;
public void uploadFile() {
.....
boxFileService.uploadFile(user, credential);
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(BoxFileDao.class)
public class BoxFileDaoTest {
@Test
public void testUploadFile() {
BoxFileDao mock = PowerMockito.spy(new BoxFileDao());
(how do I get the boxFileService from mock?)
mock.uploadFile();
verify(boxFileService).uploadFile(user, credential);
}
}
答案 0 :(得分:0)
首先,在将BoxFileDao
的模拟注入到被测类boxFileService
的同时创建您的类。然后,您可以在其上创建间谍。
例如:
BoxFileDao dao = new BoxFileDao();
dao.boxFileService = Mockito.mock(BoxFileService.class);
BoxFileDao spy = Mockito.spy(dao);
但问题是您为什么还要这么做?有理由监视BoxFileDao
,即您正在测试的班级吗?
答案 1 :(得分:0)
您可以使用@InjectMock
将模拟的boxFileService
对象注入实际的boxFileDao
对象中。您的测试课程可以写成类似
@RunWith(PowerMockRunner.class)
public class BoxFileDaoTest {
@Mock
private BoxFileService boxFileService;
@InjectMocks
private BoxFileDao boxFileDao;
@Test
public void testUploadFile() {
boxFileDao.uploadFile();
verify(boxFileService).uploadFile(user, credential);
}
}