【发布时间】:2020-12-08 15:31:35
【问题描述】:
我有一个 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"
【问题讨论】:
标签: java spring unit-testing spring-test