[英]@PostConstruct not called when using Mockito @Spy annotation
I am using Spring, TestNG and Mockito frameworks. 我正在使用Spring,TestNG和Mockito框架。 I am writing a unit test for a class A that has a dependency on class B .
我正在为A类编写一个单元测试,它依赖于B类。 Class B has a method annotated with
@PostConstruct
. B类有一个用
@PostConstruct
注释的方法。
While writing Unit test case using TestNG for class A , I am annotating an instance of class B with Mockito @Spy
in the test class. 在使用TestNG为A类编写单元测试用例时,我在测试类中使用Mockito
@Spy
注释了B类的实例。 I can see the instance of B being created properly by Mockito. 我可以看到Mockito正确创建了B的实例。 But why
@PostConstruct
code is not called when Mockito is processing @Spy
annotation? 但是,当Mockito处理
@Spy
注释时, 为什么 不调用 @PostConstruct
代码?
So, what I have done is I moved the code inside @PostConstruct
to the constructor . 所以,我所做的是将
@PostConstruct
的代码移动到构造函数中 。
Is there any way to make Mockito execute any 'Post-processing' method while processing @Spy
annotation? 在处理
@Spy
注释时,有没有办法让Mockito执行任何“后处理”方法?
Appreciate any help on this. 感谢任何帮助。
No, there isn't. 不,没有。 PostConstruct is a Spring concept.
PostConstruct是一个Spring概念。 But nothing forbids you to call it in your setup method:
但没有禁止你在你的设置方法中调用它:
@Before
public void prepare() {
MockitoAnnotations.initMocks(this);
this.b.postConstruct();
}
I solved this problem by replacing the method labeled with @PostConstruct by the constructor of the class labeled @Inject. 我通过用@Inject类的构造函数替换标有@PostConstruct的方法来解决这个问题。 Both solutions do the same and are supported by Mockito.
两种解决方案都是相同的,并得到Mockito的支持。 It is necessary to put dependence:
有必要放置依赖:
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
Before: 之前:
@Service
public class AddressMapper extends CommonMapper {
@PostConstruct
private void init() {
....
After: 后:
@Service
public class AddressMapper extends CommonMapper {
@Inject
public AddressMapper() {
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.