[英]Mockito and CDI bean injection, does @InjectMocks call @PostConstruct?
I have this code: 我有这个代码:
class Patient {
@Inject Syringe syringe;
@PostConstruct
void sayThankyouDoc() {
System.out.println("That hurt like crazy!");
}
}
@RunWith(MockitoJUnitRunner.class)
class TestCase {
@Mock
Syringe siringeMock;
@InjectMocks
Patient patient;
//...
}
I expected Mockito to call PostConstruct, but I had to add: 我希望Mockito能够调用PostConstruct,但我必须添加:
@Before
public void simulate_post_construct() throws Exception {
Method postConstruct = Patient.class.getDeclaredMethod("sayThankyouDoc", null);
postConstruct.setAccessible(true);
postConstruct.invoke(patient);
}
Is there a better way to do this? 有一个更好的方法吗?
Although not a direct answer to your question, however I suggest that you move away from field injection and use constructor injection instead (makes code more readable and testable). 虽然不能直接回答你的问题,但我建议你不要再使用字段注入并使用构造函数注入(使代码更具可读性和可测试性)。
Your code would look like: 您的代码如下所示:
class Patient {
private final Syringe syringe;
@Inject
public Patient(Syringe syringe) {
System.out.println("That hurt like crazy!");
}
}
Then your test would simply be: 那你的测试就是:
@RunWith(MockitoJUnitRunner.class)
class TestCase {
@Mock
Syringe siringeMock;
Patient patient;
@Before
public void setup() {
patient = new Patient(siringeMock);
}
}
Update 更新
As suggested by Erik-Karl in the comments, you could use @InjectMocks
to get rid of the setup method. 正如Erik-Karl在评论中所建议的那样,你可以使用@InjectMocks
来摆脱设置方法。 The solution works because Mockito will use the appropriate constructor injection (as described here ). 解决方案的工作,因为会的Mockito使用适当的构造函数注入(如描述在这里 )。 The code would then look like: 然后代码看起来像:
@RunWith(MockitoJUnitRunner.class)
class TestCase {
@Mock
Syringe siringeMock;
@InjectMocks
Patient patient;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.