Spring Boot测试,无法加载属性文件进行junit测试

时间:2018-08-27 02:48:53

标签: spring-boot junit

这是我的项目结构

src/main/java
            /main/ApplicationContext.java
src/main/resource/
            /application-context.xml
            /conf/soap.properties
src/test/java
            /main/TestApplicationContext.java           
src/test/resource/
            /application-context-test.xml
            /confTest/soapTest.properties

然后TestApplicationContext.java

@SpringBootApplication
@ImportResource("classpath:application-context-test.xml")
@ActiveProfiles("test")
public class TestApplicationContext {

  public static void main(String[] args) {
    SpringApplication.run(TestApplicationContext.class, args);
  }

}

以及如何加载Junit测试专用的属性

@ActiveProfiles("test")
@SpringBootTest
@ContextConfiguration(classes = {TestApplicationContext.class})
@AutoConfigureWireMock(port = 8081, httpsPort = 443)
@TestPropertySource(locations = {"classpath:confTest/soapTest.properties"})
@RunWith(SpringJUnit4ClassRunner.class)

public class ApplicationTest {
    @Test
    void testABC(){
        //test here
    }
}

但是似乎confTest/soapTest.properties文件中的属性无法在运行时加载

显示消息 Could not resolve placeholder 'service.test.url' in value "${service.test.url}"

实际上service.test.urlsoapTest.properties中可用

我知道这可能是一个重复的问题,但是我用Google搜索并尝试了许多解决方案,但对我不起作用

我的配置有问题吗

1 个答案:

答案 0 :(得分:0)

@Ryo ...使用这个 您可以在测试类中使用@TestPropertySource批注。

例如,您在mailing.properties文件中具有以下属性:

mailFrom=fromMe@mail.com

只需在测试类上注释@TestPropertySource("classpath:config/mailing.properties")

例如,您应该能够使用@Value注释读出属性。

@Value("${fromMail}")
private String fromMail;

为避免在多个测试类上对此注释添加注释,您可以实现超类或元注释。

EDIT1:

@SpringBootApplication
@PropertySource("classpath:config/mailing.properties")
public class DemoApplication implements CommandLineRunner {

@Autowired
private MailService mailService;

public static void main(String[] args) throws Exception {
    SpringApplication.run(DemoApplication.class, args);
}

@Override
public void run(String... arg0) throws Exception {
    String s = mailService.getMailFrom();
    System.out.println(s);
}

MailService:

@Service
public class MailService {

    @Value("${mailFrom}")
    private String mailFrom;

    public String getMailFrom() {
        return mailFrom;
    }

    public void setMailFrom(String mailFrom) {
        this.mailFrom = mailFrom;
    }
}

DemoTestFile:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = DemoApplication.class)
@TestPropertySource("classpath:config/mailing.properties")
public class DemoApplicationTests {

    @Autowired
    MailService mailService;

    @Test
    public void contextLoads() {
        String s = mailService.getMailFrom();
        System.out.println(s);
    }
}

是@Ryo ....您的正确 使用这个@Order(Ordered.HIGHEST_PRECEDENCE + 99)