java 如何模拟在方法内部创建的对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26320127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to mock objects created inside method?
提问by daydreamer
Consider this
考虑这个
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));
}
}
I want to mock out
我想嘲笑
new UserQueries(crudService)
so that I can mock out its behavior
这样我就可以模拟它的行为
Any ideas?
有任何想法吗?
回答by troig
With PowerMockyou can mock constructors. See example
使用PowerMock,您可以模拟构造函数。查看示例
I'm not with an IDE right now, but would be something like this:
我现在没有 IDE,但会是这样的:
UserQueries userQueries = PowerMockito.mock(UserQueries.class);
PowerMockito.whenNew(UserQueries.class).withArguments(Mockito.any(CrudService.class)).thenReturn(userQueries);
You need to run your test with PowerMockRunner
(add these annotations to your test class):
您需要运行您的测试PowerMockRunner
(将这些注释添加到您的测试类):
@RunWith(PowerMockRunner.class)
@PrepareForTest(UserQueries .class)
If you cannot use PowerMock, you have to inject a factory, as it says @Briggo answer.
如果你不能使用 PowerMock,你必须注入一个工厂,正如@Briggo 的回答所说。
Hope it helps
希望能帮助到你
回答by Briggo
You could inject a factory that creates UserQueries.
您可以注入一个创建 UserQueries 的工厂。
public class UserManager {
private final CrudService crudService;
private final UserQueriesFactory queriesFactory;
@Inject
public UserManager(@Nonnull final CrudService crudService,UserQueriesFactory queriesFactory) {
this.crudService = crudService;
this.queriesFactory = queriesFactory;
}
@Nonnull
public List<UserPresentation> getUsersByState(@Nonnull final String state) {
return UserPresentation.getUserPresentations(queriesFactory.create(crudService).getUserByState(state));
}
}
}
Although it may be better (if you are going to do this) to inject your CrudService into the factory.
尽管将您的 CrudService 注入工厂可能会更好(如果您打算这样做)。