SpringBoot-Junit无法在junit中加载配置属性

时间:2018-11-23 21:01:13

标签: java spring-boot properties

我有一个consumer.properties文件,该文件在src/main/resources中具有以下内容,以及一个随附的Configuration类,该类将文件的内容加载并存储到类成员变量中:

// consumer.properties文件在src/main/resources中:

com.training.consumer.hostname=myhost
com.training.consumer.username=myusername
com.training.consumer.password=mypassword

// ConsumerConfig.java

@Configuration
@PropertySource(
        value= {"classpath:consumer.properties"}
        )
@ConfigurationProperties(prefix="com.training.consumer")
public class ConsumerConfig {

    private String hostname;
    private String username;
    private String password;

    public ConsumerConfig() { }

    public String getHostname() {
        return hostname;
    }
    public void setHostname(String hostname) {
        this.hostname = hostname;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "ConsumerConfig [hostname=" + hostname + ", username=" + username + ", password=" + password + "]";
    }
}

我还有一个ConfigsService类,可以自动装配ConsumerConfig类以检索各个属性:

@Component
public class ConfigsService {

    @Autowired
    ConsumerConfig consumerConfig;

    public ConsumerConfig getConsumerConfig() {
        return consumerConfig;
    }

    public void showConfig() {
        consumerConfig.toString();
    }

    public ConsumerConfig getConfig() {
        return consumerConfig;
    }
}

运行ConfigsService的方法时,可以很好地加载属性。问题出在单元测试中,在调用configService.getConfig().getHostname()时会抛出NPE -即使在创建了src/test/resources目录,在其中添加我的consumer.properties文件并自动在测试:

@TestPropertySource("classpath:consumer.properties")
public class ConfigsServiceTest {

    @Autowired
    ConsumerConfig consumerConfig;

    @InjectMocks
    ConfigsService configService;


    @Before
    public void beforeEach() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void someTest() {
        System.out.println(configService.getConfig().getHostname()); //Throws Null Pointer Exception here.
        Assert.assertTrue(true);
    }
}

0 个答案:

没有答案
相关问题