SpringBoot单元测试

2018-11-07  本文已影响0人  MrJonny

在测试类中读取某个application-开头的propertiesyaml中的属性

命名规则

通过@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

例子

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);
    }

}
上一篇 下一篇

猜你喜欢

热点阅读