【问题标题】:@PostConstruct not running within Spring test@PostConstruct 没有在 Spring 测试中运行
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 这个 sn-p 中的 MyService bean 来自哪里?
    • @SpringBootTest 是做什么的?它是否执行组件扫描?该扫描是否会包括他们的 MyService 类所在的包?
    • @SotiriosDelimanolis SpringBootTest 创建了一个完整的 spring 上下文,用于大量冗余和缓慢的单元测试。
    • @Gimby 该上下文会创建/包含MyService bean吗?
    • @nkrivenko 谢谢!我的代码中缺少的部分是 @SpringBootTest@Autowire
    猜你喜欢
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 2012-10-25
    • 2021-06-14
    相关资源
    最近更新 更多