[英]Using property values in JUnit test classes without load whole Spring Boot application context
I have a Spring Boot Component as below我有一个 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);
}
}
How do I write a test class where Client class automatically use the resource/application.yaml in the test classpath, without loading the whole application context?如何编写测试 class 客户端 class 自动使用资源/application.yaml 在测试类路径中,而不加载整个应用程序上下文? I want to use like below:
我想像下面这样使用:
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();
}
}
The test class above throws:上面的测试 class 抛出:
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)}
I don't want to load the whole application context just for secretKey thing because it is expensive.我不想仅仅为 secretKey 加载整个应用程序上下文,因为它很昂贵。
I also don't want to create a constructor and manually give the key myself.我也不想创建一个构造函数并自己手动提供密钥。
Main reason for this exception is without loading your class Client in springContext, you are trying to read it.此异常的主要原因是没有在 springContext 中加载您的 class 客户端,您正在尝试阅读它。 So you are getting
NoSuchBeanDefinitionException
所以你得到
NoSuchBeanDefinitionException
You need to do 2 things.你需要做两件事。
@ContextConfiguration(classes = Client.class)
@ContextConfiguration(classes = Client.class)
在上下文中加载 classapplication.yaml
from src folder as you are not having it in test/resource folder as @TestPropertySource(locations = "/application.yaml")
application.yaml
因为你没有在 test/resource 文件夹中作为@TestPropertySource(locations = "/application.yaml")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.