java—在junit测试类中使用属性值而不加载整个spring启动应用程序上下文

lokaqttq  于 2021-07-23  发布在  Java
关注(0)|答案(1)|浏览(757)

我有一个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);
    }

}

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

}

上面的测试类抛出:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.nerdility.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加载整个应用程序上下文,因为它很昂贵。
我也不想创建一个构造函数,然后自己手动给出密钥。

mo49yndu

mo49yndu1#

出现此异常的主要原因是没有在springcontext中加载类客户机,您正在尝试读取它。所以你得到了 NoSuchBeanDefinitionException 你需要做两件事。
使用类注解在上下文中加载类 @ContextConfiguration(classes = Client.class) 显式加载 application.yaml 从src文件夹,因为您没有将它作为测试/资源文件夹 @TestPropertySource(locations = "/application.yaml")

相关问题