如何模拟在方法内部创建的对象? [英] How to mock objects created inside method?
本文介绍了如何模拟在方法内部创建的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑这个
public class UserManager {
private final CrudService crudService;
@Inject
public UserManager(@Nonnull final CrudService crudService) {
this.crudService = crudService;
}
@Nonnull
public List<UserPresentation> getUsersByState(@Nonnull final String state) {
return UserPresentation.getUserPresentations(new UserQueries(crudService).getUserByState(state));
}
}
我要模拟
new UserQueries(crudService)
以便我可以模拟其行为
有什么想法吗?
推荐答案
With PowerMock you can mock constructors. See example
我现在没有使用IDE,但是会是这样的:
I'm not with an IDE right now, but would be something like this:
UserQueries userQueries = PowerMockito.mock(UserQueries.class);
PowerMockito.whenNew(UserQueries.class).withArguments(Mockito.any(CrudService.class)).thenReturn(userQueries);
您需要使用PowerMockRunner
运行测试(将这些注释添加到测试类中):
You need to run your test with PowerMockRunner
(add these annotations to your test class):
@RunWith(PowerMockRunner.class)
@PrepareForTest(UserQueries .class)
如果您不能使用PowerMock,则必须注入一个工厂,因为它显示@Briggo答案.
If you cannot use PowerMock, you have to inject a factory, as it says @Briggo answer.
希望有帮助
这篇关于如何模拟在方法内部创建的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文