在 JUnit 测试中使用 属性 值 类 不加载整个 Spring 引导应用程序上下文

Using property values in JUnit test classes without load whole Spring Boot application context

我有一个 Spring 引导组件,如下所示

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);
    }

}

如何编写测试 class,其中客户端 class 自动使用测试 class 路径中的 resource/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();
    }

}

上面的测试 class 抛出:

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 加载整个应用程序上下文,因为它很昂贵。

我也不想创建构造函数,自己手动给key

出现此异常的主要原因是没有在 springContext 中加载 class 客户端,您正在尝试读取它。所以你得到 NoSuchBeanDefinitionException

你需要做两件事。

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