SpringBoot單元測試

Genee發表於2018-11-07

在測試類中讀取某個application-開頭的propertiesyaml中的屬性

命名規則

  • 必須以application-開頭
    • application-dev.properties
    • application-test.properties
    • application-dev.yml
    • application-dev.yml

通過@ActiveProfiles來指定使用哪個檔案

例子

package com.atgenee.demo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test") //指定使用application-test.yml
public class TestApplicationTests {

    @Value("${user.first-name}")
    private String firstName;

    @Value("${user.weight}")
    private Integer weight;

    @Test
    public void hei() {
        System.out.println(firstName);
        System.out.println(weight);
    }

}
複製程式碼

@TestPropertySource

  • 載入指定配置檔案
  • 可以是properties檔案,也可以是yaml

例子

package com.atgenee.demo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(properties = { "spring.config.location = classpath:test.properties" })
public class TestApplicationTests {

    @Value("${user.first-name}")
    private String firstName;

    @Value("${user.weight}")
    private Integer weight;

    @Test
    public void hei() {
        System.out.println(firstName);
        System.out.println(weight);
    }

}
複製程式碼

相關文章