@PostConstruct 不是 运行 在 Spring 测试中

@PostConstruct not running within Spring test

我有一个 Service class 和一个 @PostConstruct 方法,应该初始化一个参数。

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

我想这真的很愚蠢:

@Service
public class MyService {

private String s;

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

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

测试class:

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 运行ning 时 - 右键单击​​并 运行 测试,或者当 运行ning 通过 gradle test 的控制台时:

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

您使用 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");
    }

}