java - 值注释在 Junit 测试中不起作用
问题描述
@SpringBootTest
public class RuleControllerTest {
@Value("${myUrl}")
private String myUrl;
private HttpClient httpClient = HttpClients.createDefault();
@Test
public void loadAllRules() throws IOException, URISyntaxException {
String target = myUrl + "/v2/rules";
String json = generateHTTPget(target);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Rule[] rules = objectMapper.readValue(json, Rule[].class);
boolean correctResponse = rules != null ? true : false;
int httpCode = getHTTPcode(target);
boolean correctStatus = httpCode >= 200 && httpCode <= 300 ? true : false;
assertTrue(correctStatus);
assertTrue(correctResponse);
}
我正在尝试从我的 application.properties 文件中获取一个字符串,并将 @Value 插入到我的 Junit 测试的字段中。我以前在普通课上做过这个,但是我在测试中的字段上是空的。我阅读了有关此问题的类似问题,并且到目前为止尝试创建 src/test/resources 包并在那里克隆 application.properties。还尝试添加依赖项
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
并添加注释
@RunWith(SpringRunner.class)
我收到一条消息 No tests found with test runner Junit 5 并且在 Problems 选项卡中我有 springboottest.jar 无法读取或不是有效的 ZIP 文件
也试过
@PropertySource("classpath:application.properties")
作为类注释,但结果相同
我也尝试过:
@RunWith(SpringJUnit4ClassRunner.class)
如果我将 String myUrl 硬编码为“ http://localhost:8090 ”,则测试有效,因此问题出在 @Value 不起作用
解决方案
以下对我有用。它从 application.properties 文件中获取值。
@RunWith(SpringRunner.class)
@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)
public class ValueAnnotationTest {
@Value("${myUrl}")
private String myUrl;
@Test
public void test1() throws Exception {
assertThat(myUrl).isEqualTo("http://test.com");
}
}
单独使用
ConfigFileApplicationContextInitializer
不支持@Value("${…}")
注入。它唯一的工作是确保将application.properties
文件加载到 Spring 的环境中。为了获得@Value
支持,您需要另外配置 aPropertySourcesPlaceholderConfigurer
或 use@SpringBootTest
,它会为您自动配置一个。
推荐阅读
- reactjs - Memoize 自定义钩子的返回值
- javascript - 在 React/JavaScript 中为二维数组赋值
- ecmascript-6 - 未捕获的类型错误:代理上的“ownKeys”:陷阱结果不包括“长度”
- python - 将 `runpy` 与 mock 组合在单独运行时通过,但在与其他测试一起运行时失败
- python - 为什么我不能在 pyqt5 gui 中嵌入的 matplotlib 颜色图中成功绘制感兴趣区域?
- java - Springboot - 在@Async方法中调用@Transactional方法,事务不起作用
- db2 - 日志接收器中没有删除条目?
- python - 如何为 Django 应用程序定义基本 style.css 文件
- python - 如何在循环中的每个变量中添加一个值?
- pandas - 在 Pandas UDF 中,是否可以返回包含嵌套列表的系列?