junit @WebMvcTest未找到buildProperties

chhqkbe1  于 11个月前  发布在  其他
关注(0)|答案(3)|浏览(188)

我为我的MVC控制器做了JUnit测试。现在我想在每个页面的页脚显示构建号,所以我在我的thymeleaf模板中添加了以下div:

<div class="versionInfo">Version <span th:text="${@buildProperties.getVersion()}"></span></div>

现在测试失败:
由于:org.springframework.beans.factory.NoSuchBeanDefinitionException:没有名为“buildProperties”的Bean可用
我试着把它作为一个模拟,但无济于事:

@MockBean
private BuildProperties buildProperties;

或者遵循this advice(请参阅我在答案下方的评论)。
那么,我如何才能让我的测试再次与BuildProperties工作?

hlswsv35

hlswsv351#

当您尝试通过以下方式访问Bean时:${@buildProperties.getVersion()}它实际上是一个SpEL表达式,用于通过BeanReference访问bean。不幸的是,它没有默认值,如果找不到bean,它不会返回null,而是抛出一个异常。
我不知道有什么简单的方法可以通过SpEL检查bean是否存在于上下文中。
所以我认为最好的解决方案是创建一个嵌套的测试配置类,并在那里定义一个默认的BuildProperties bean。

@TestConfiguration
public static class TestConfig {    
  @Bean 
  BuildProperties buildProperties() {
    return new BuildProperties(new Properties());
  }
}

或者,如果您需要在多个测试类中进行额外的配置,您可以将其创建为一个单独的类并使用@Import(TestConfig.class)。

nbewdwxp

nbewdwxp2#

如果您使用的是gradle,只需将以下内容添加到您的build.grandle文件:

SpringBoot { buildInfo() }

配置完spring-boot-maven-plugin之后,你就可以构建应用程序并访问有关应用程序构建的信息。BuildProperties对象由Spring(@Autowired)注入

toe95027

toe950273#

将@WebMvcTest更改为完整的@SpringBootTest可以解决这个问题,因为这样就会执行ProjectInfoAutoConfiguration。由于我想坚持使用@WebMvcTest,我将ProjectInfoAutoConfiguration包含到我的WebMvcTest中:

@WebMvcTest(YOUR_CONTROLLER_HERE.class)
@ImportAutoConfiguration(ProjectInfoAutoConfiguration.class)
class YOUR_CONTROLLER_HERETest{
    // Use at your will
    @Autowired
    private BuildProperties buildProperties;
}

当然,只有正确配置了Sping Boot Maven Plugin,这才能起作用。

相关问题