我很难用
@TestPropertySource
我测试中的价值
以下是MRE:
import jakarta.annotation.PostConstruct;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@ConfigurationProperties(prefix = "my-app")
public class GatewayMeta {
@Value("${server.port}")
private String port;
@Setter
@Getter
private List<Server> servers;
@PostConstruct
private void init() {
if (servers == null) {
servers = List.of("http://localhost:" + port);
}
}
}
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = ServerPropertiesTest.ServerPropertiesTestConfig.class)
class ServerPropertiesTest {
@Autowired
ServerProperties serverProperties;
@Test
void ifNoServerSpecified_serversHasOneServerMatchingLocalhostServerPort() {
List<String> servers = serverProperties.getServers();
assertThat(servers).hasSize(1);
String server = servers.get(0);
assertThat(server).isEqualTo("http://localhost:8080");
}
@Configuration
@EnableConfigurationProperties(ServerProperties.class)
@Import(PropertySourcesPlaceholderConfigurer.class)
@TestPropertySource(properties = "server.port=8080")
static class ServerPropertiesTestConfig {
}
}
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'server.port' in value "${server.port}"
我还尝试指定一个
.properties
文件在
locations
(也许,
properties
只丰富现有的属性?)
@TestPropertySource(locations = "classpath:application-test.properties",
properties = "server.port=8080")
无论是否,结果都是一样的
*.properties
是否包含密钥。看起来
PropertySourcesPlaceholderConfigurer
不在乎我的
@测试属性源
完全
我也试过这个:
@Configuration
@EnableConfigurationProperties(ServerProperties.class)
@Import(PropertySourcesPlaceholderConfigurer.class)
@PropertySource("classpath:application-test.properties")
@TestPropertySource(properties = "server.port=8000")
static class GatewayMetaTestConfig {
}
没有例外,但是
@测试属性源
完全忽略,其值不会覆盖中指定的值
.properties
文件
有一些吗
其他
*PostProcessor
对于
@测试属性源
(不是
属性来源占位符配置器
)我需要进口吗?
我访问了这些类似的帖子,但它们似乎没有帮助:
1
,
2
,
3
我的错误是什么?