[英]How to mock a member in the Class that you spy with powermockito
How can I mock a member class in another class which has already been spied by PowerMockito.spy()?如何在另一个 class 中模拟成员 class 已经被 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);
}
}
First you create your class under test BoxFileDao
while injecting the mock for boxFileService
into it.首先,您在测试
BoxFileDao
下创建 class,同时将boxFileService
的模拟注入其中。 Afterwards you can create the spy on it.之后,您可以在其上创建间谍。
For example:例如:
BoxFileDao dao = new BoxFileDao();
dao.boxFileService = Mockito.mock(BoxFileService.class);
BoxFileDao spy = Mockito.spy(dao);
But the question would be why do you even want to do that?但问题是你为什么要这样做? Is there a reason to spy on
BoxFileDao
, your class under test?是否有理由监视
BoxFileDao
,您的 class 正在测试中?
You can use @InjectMock
to inject the mocked boxFileService
object in the real boxFileDao
object.您可以使用
@InjectMock
将boxFileService
的boxFileService object 注入到真实的boxFileDao
object 中。 Your test class can be written something like您的测试 class 可以写成类似
@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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.