首页 > 解决方案 > @PostConstruct 未在 Spring 测试中运行

问题描述

我有一个Service带有@PostConstruct应该初始化参数的方法的类。

然后一个常规的方法是使用这个参数。即使在常规运行中这按预期工作,但在单元测试期间@PostConstruct会跳过并且参数未初始化。

我想这真的很愚蠢:

@Service
public class MyService {

private String s;

@PostConstruct
public void init(){
    s = "a";
}

public String append(String a){
    return s+ a;
}
}

测试类:

import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)  //  <------- tried with and without
public class MyServiceTest {

@Test
public void testXYZ(){
    Assertions.assertThat(new MyService().append("b")).isEqualTo("ab");
}

}

运行结果(从 IntelliJ 运行时 - 右键单击​​并运行测试,或通过控制台运行时gradle test):

org.opentest4j.AssertionFailedError: 
Expecting:
   <"nullb">
to be equal to:
   <"ab">
but was not.
Expected :"ab"
Actual   :"nullb"

标签: javaspringunit-testingspring-test

解决方案


new您使用关键字手动创建一个对象,该@PostConstruct方法由 Spring DI 容器在 Spring 管理的组件上调用,因此它不适用于手动创建的对象。

这将按您的预期工作:

import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;

import org.springframework.boot.test.context.SpringBootTest;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyServiceTest {

    @Autowired
    private MyService service;

    @Test
    public void testXYZ(){
        Assertions.assertThat(service.append("b")).isEqualTo("ab");
    }

}

推荐阅读