java - @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"
解决方案
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");
}
}
推荐阅读
- html - 如何在浏览器中查看 PDF 或 DOC 文件
- postgresql - Inserting string into jsonb type postgres
- javascript - 如何将文本文件(特定格式)上传到烧瓶应用程序中的 java 脚本数组?
- git - will using git interfere with bixby IDE?
- c# - How to pass object with input value to controller post method
- .net - 解码驾驶执照 PDF417 或磁条
- scala - sbt 找不到参数 valName 的隐式值
- java - 如何在android studio中处理双击事件onclicklistener?
- python-3.x - python3 错误 JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1,在 Ubuntu 中跳过解锁
- php - laravel 有什么方法可以在多对多关系中找到数据透视表中不存在的那些值?