【发布时间】:2019-02-17 00:00:40
【问题描述】:
@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 文件中获取一个字符串,并在我的 Junit 测试的一个字段中插入 @Value。我以前在普通课堂上做过这个,但我在测试中的字段上为空。我阅读了有关此问题的类似问题,并且到目前为止尝试创建 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)
如果我将字符串 myUrl 硬编码为“http://localhost:8090”,则测试有效,因此问题在于 @Value 不起作用
【问题讨论】:
-
你可以试试this
-
请添加您的测试...仅添加一些 sn-ps 是行不通的。
-
@M.Deinum 确实 :))我添加了我的测试现在的样子
-
你至少需要一个
@RunWith(SpringRunner.class)来测试方法。@SpringBootTest现在几乎没用了。 -
@M.Deinum 这只是我尝试的最新方法......使用 RunWith(SpringRunner.class) 我得到 java.net.URISyntaxException: Illegal character in path at index 1: ${myUrl} /v2/rules 我不确定为什么 Uri 会这样开始