java Mockito:将类模拟注入私有接口字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26069543/
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
Mockito: inject a class mock into a private interface field
提问by zongweil
I'm using Mockito 1.9.5 to do some unit testing. I'm trying to inject a concrete class mock into a class that has a private interface field. Here's an example:
我正在使用 Mockito 1.9.5 进行一些单元测试。我试图将一个具体的类模拟注入一个具有私有接口字段的类。下面是一个例子:
Class I'm testing
我正在测试的课程
@Component
public class Service {
@Autowired
private iHelper helper;
public void doSomething() {
helper.helpMeOut();
}
}
My test for this class
我对这门课的测试
@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {
@Mock
private iHelper helper;
@InjectMocks
private Service service;
@Before
public void setup() {
service = new Service();
}
@Test
public void testStuff() {
doNothing().when(helper).helpMeOut();
service.doSomething();
}
}
This code throws a NullPointerException when trying to call helper.helpMeOut() in doSomething(). I debugged and found that helper was null when running the test. I also tried changing iHelper to the concrete class Helper, and the same issue happened.
当尝试在 doSomething() 中调用 helper.helpMeOut() 时,此代码会抛出 NullPointerException。我调试了下,运行测试时发现helper为null。我还尝试将 iHelper 更改为具体类 Helper,但发生了同样的问题。
Any suggestions? How can I get Mockito to correctly inject a mock into an interface private field?
有什么建议?如何让 Mockito 正确地将模拟注入接口私有字段?
采纳答案by zongweil
@acdcjunior's comment helped me figure out the issue. Instantiating service using the new keyword caused Spring to not inject the dependencies (in this case helper) correctly. I fixed this by autowiring in service in the test. My final working code looks like this:
@acdcjunior 的评论帮助我解决了这个问题。使用 new 关键字实例化服务会导致 Spring 无法正确注入依赖项(在本例中为 helper)。我通过在测试中自动装配服务解决了这个问题。我的最终工作代码如下所示:
Class I'm testing
我正在测试的课程
@Component
public class Service {
@Autowired
private iHelper helper;
public void doSomething() {
helper.helpMeOut();
}
}
My test for this class
我对这门课的测试
@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {
@Mock
private iHelper helper;
@InjectMocks
@Autowired
private Service service;
@Test
public void testStuff() {
doNothing().when(helper).helpMeOut();
service.doSomething();
}
}
Hope this helps someone else. Thanks for the suggestions!
希望这对其他人有帮助。感谢您的建议!
回答by Alexander Campos
According to the docsyou are missing the setup.
根据文档,您缺少设置。
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
Edited*
已编辑*
Take at look at this page why you should not use @InjectMock to autowire fields