@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)
我收到一条消息,未找到测试运行程序Junit 5的测试,并且在“问题”选项卡中我无法读取springboottest.jar或该文件不是有效的ZIP文件
也尝试过
@PropertySource("classpath:application.properties")
作为类批注,但结果相同
我也尝试过:
@RunWith(SpringJUnit4ClassRunner.class)
如果我将字符串myUrl硬编码为“ http://localhost:8090”,则测试有效,因此问题出在@Value不起作用
答案 0 :(得分:2)
以下对我有用。它从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");
}
}
答案 1 :(得分:1)
尝试在测试课程上使用@TestPropertySource
。
答案 2 :(得分:0)
请在下面使用以获得Junit中变量的值
ReflectionTestUtils.setField(YOURCONTROLLER, "variableName", valueOfString);
如果变量为boolean的示例。另外,变量名应与控制器中的变量名相同。
ReflectionTestUtils.setField(myController, "isFlag", true);
此外,您将需要添加pom依赖项
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.0.RELEASE</version>
<type>jar</type>
<scope>test</scope>
</dependency>
答案 3 :(得分:0)
您需要添加
@PropertySource("classpath:test.properties")
例如:
@Configuration
@ComponentScan(basePackages = { "com.app.*" })
@PropertySource("classpath:test.properties")
public class MyAppConfig {
///
}
如果您需要不同的配置来测试或覆盖application.properties中的值
@TestPropertySource(locations="classpath:test.properties")
例如:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyApplication.class)
@TestPropertySource(locations="classpath:test.properties")
public class MyApplicationTests {
}