Java 使用 Mockito @Spy 注释时不调用 @PostConstruct

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21957918/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:38:56  来源:igfitidea点击:

@PostConstruct not called when using Mockito @Spy annotation

javaspringannotationsmockito

提问by javalearner

I am using Spring, TestNG and Mockito frameworks. I am writing a unit test for a class Athat has a dependency on class B. Class Bhas a method annotated with @PostConstruct.

我正在使用 Spring、TestNG 和 Mockito 框架。我正在为A类编写单元测试,该类依赖于B类。B类有一个用@PostConstruct.

While writing Unit test case using TestNG for class A, I am annotating an instance of class Bwith Mockito @Spyin the test class. I can see the instance of Bbeing created properly by Mockito. But why@PostConstructcode is not calledwhen Mockito is processing @Spyannotation?

在使用 TestNG 为A类编写单元测试用例时,我在测试类中使用 Mockito注释B类的实例@Spy。我可以看到Mockito 正确创建了B的实例。但是为什么在 Mockito 处理注解的时候不调用@PostConstruct代码呢?@Spy

So, what I have done is I moved the code inside @PostConstructto the constructor.

所以,我所做的是将代码@PostConstruct移到了构造函数中

Is there any way to make Mockito execute any 'Post-processing' method while processing @Spyannotation?

有没有办法让 Mockito 在处理@Spy注释时执行任何“后处理”方法?

Appreciate any help on this.

感谢您对此的任何帮助。

采纳答案by JB Nizet

No, there isn't. PostConstruct is a Spring concept. But nothing forbids you to call it in your setup method:

不,没有。PostConstruct 是一个 Spring 概念。但是没有什么禁止你在你的设置方法中调用它:

@Before
public void prepare() {
    MockitoAnnotations.initMocks(this);
    this.b.postConstruct();
}

回答by leon cio

I solved this problem by replacing the method labeled with @PostConstruct by the constructor of the class labeled @Inject. Both solutions do the same and are supported by Mockito. It is necessary to put dependence:

我通过用标记为@Inject 的类的构造函数替换标记为@PostConstruct 的方法解决了这个问题。两种解决方案都做同样的事情,并得到 Mockito 的支持。有必要把依赖:

    <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() {
            ...