値の注釈は、JUnitテストで動作しません

ゲオルギMichev:
@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が動作していない中での試験工事ので、問題があります

Ritesh:

私のために作品を以下に示します。これは、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あなたのために、自動設定するものを。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=200401&siteId=1