@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を挿入しようとしています。私は、通常のクラスの前にこれを行っているが、私は、テスト中に私のフィールドにはnullを持っています。私はこの問題についての同様の質問を読んで、これまでに存在しapplication.propertiesのsrc /テスト/リソースパッケージおよびクローンを作成しようとしました。また、依存関係を追加しようとしました
<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が動作していない中での試験工事ので、問題があります
私のために作品を以下に示します。これは、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
のサポート、あなたはどちらかに加えて設定する必要がありますPropertySourcesPlaceholderConfigurer
または使用の@SpringBootTest
あなたのために、自動設定するものを。