【问题标题】:Using property values in JUnit test classes without load whole Spring Boot application context在 JUnit 测试类中使用属​​性值而不加载整个 Spring Boot 应用程序上下文
【发布时间】:2021-06-08 17:27:34
【问题描述】:

我有一个如下的 Spring Boot 组件

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class Client {

    @Value("${SecretKey}") private String secretKey;
    
    public void createAccount() {
        log.error("secretKey" + secretKey);
    }

}

如何编写一个测试类,其中客户端类自动使用测试类路径中的资源/application.yaml,而不加载整个应用程序上下文?我想像下面这样使用:

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@Slf4j
@ExtendWith(SpringExtension.class)
public class ClientTest {

    @Autowired
    private Client client;

    @DisplayName("Create Client")
    @Test
    public void givenX_thenCreateAccount() throws Exception {
       client.createAccount();
    }

}

上面的测试类抛出:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.payment.stripe.ClientTest': Unsatisfied dependency expressed through field 'client'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'Client' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

我不想只为 secretKey 加载整个应用程序上下文,因为它很昂贵。

我也不想创建构造函数并自己手动提供密钥。

【问题讨论】:

    标签: java spring spring-boot junit5


    【解决方案1】:

    这个异常的主要原因是没有在springContext中加载你的类客户端,你正在尝试阅读它。所以你得到NoSuchBeanDefinitionException

    你需要做两件事。

    1. 使用类注释@ContextConfiguration(classes = Client.class) 在上下文中加载您的类
    2. 从 src 文件夹中显式加载 application.yaml,因为您在 test/resource 文件夹中没有 @TestPropertySource(locations = "/application.yaml")

    【讨论】:

      猜你喜欢
      • 2018-07-11
      • 2015-04-27
      • 2021-08-02
      • 2013-02-03
      • 2019-03-16
      • 2020-09-07
      • 1970-01-01
      • 1970-01-01
      • 2021-06-23
      相关资源
      最近更新 更多