Spring Boot-Junit无法在junit测试中加载配置属性

时间:2018-11-23 20:47:28

标签: java spring spring-boot properties

我有一个LoadError: [91msyntax: unexpected "end"[39m while loading C:\Users\username\Desktop\Study\zad1.jl, in expression starting on line 60 include_string(::String, ::String) at loading.jl:522 include_string(::Module, ::String, ::String) at Compat.jl:84 (::Atom.##112#116{String,String})() at eval.jl:109 withpath(::Atom.##112#116{String,String}, ::String) at utils.jl:30 withpath(::Function, ::String) at eval.jl:38 hideprompt(::Atom.##111#115{String,String}) at repl.jl:67 macro expansion at eval.jl:106 [inlined] (::Atom.##110#114{Dict{String,Any}})() at task.jl:80 文件,该文件在consumer.properties中具有以下内容,以及一个随附的Configuration类,该类将文件的内容加载并存储到类成员变量中:

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

src/main/resources

// ConsumerConfig.java

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

我还有一个@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

运行ConfigsService的方法时,可以很好地加载属性。问题出在单元测试中,在调用@Component public class ConfigsService { @Autowired ConsumerConfig consumerConfig; public ConsumerConfig getConsumerConfig() { return consumerConfig; } public void showConfig() { consumerConfig.toString(); } public ConsumerConfig getConfig() { return consumerConfig; } } 时返回空值-即使在创建了configService.getConfig().getHostname()目录并在其中添加我的src/test/resources文件之后:

consumer.properties

2 个答案:

答案 0 :(得分:3)

由于模拟对象,您将获得空值。我建议将SpringRunner与上下文配置一起使用,这将加载config类中的属性并创建bean。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ConsumerConfig.class, ConfigsService.class})
@TestPropertySource(locations = "classpath:consumer.properties")
public class ConfigsServiceTest {

  @Autowired
  private ConfigsService configsService;

  @Test
  public void someTest() {
    Assert.assertNotNull(configService.getConfig().getHostname());
  }
}

答案 1 :(得分:0)

错误可能是因为在ConfigsServiceTest类中您正在确定ConsumerConfig是一个Mock,这就是为什么如果删除该代码后它不会加载配置,则它不会加载