@WebMvcTest找不到buildProperties [英] @WebMvcTest does not find buildProperties
问题描述
我的MVC控制器具有有效的JUnit测试.现在,我想在每个页面的页脚中显示内部版本号,因此在我的百里香模板中添加了以下div:
I have working JUnit tests for my MVC controllers. Now I wanted to display the build number in the footer of every page, so I added the following div in my thymeleaf templates:
<div class="versionInfo">Version <span th:text="${@buildProperties.getVersion()}"></span></div>
现在测试失败,并显示以下信息:
Now the test fail with:
起因: org.springframework.beans.factory.NoSuchBeanDefinitionException:否 名为"buildProperties"的bean可用
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'buildProperties' available
我试图将其作为模拟添加,但无济于事:
I tried to add it as a mock to no avail:
@MockBean
private BuildProperties buildProperties;
或遵循此建议(请参见答案下方的我的评论).
Or following this advice (see my comment below the answer).
那么如何使BuildProperties
再次运行我的测试?
So how can I make my tests work again with the BuildProperties
?
推荐答案
当您尝试通过以下方式访问bean时:${@buildProperties.getVersion()}
实际上是通过BeanReference访问bean的SpEL表达式.不幸的是,它没有默认值,如果找不到该bean,它会返回一个异常,而不是返回null
.
When you try to access a bean via the following way: ${@buildProperties.getVersion()}
it's actually a SpEL expression for accessing a bean via a BeanReference. Unfortunately it has no default value and instead of returning null
it throws an exception if the bean cannot be found.
我不知道通过SpEL检查上下文中是否存在bean的任何简便方法.
I don't know any easy way to check if a bean exists in the context via SpEL.
因此,我认为最好的解决方案是创建一个嵌套的测试配置类并在那里定义一个默认的BuildProperties bean.
So I think the best solution if you create a nested test configuration class and define a default BuildProperties bean there.
@TestConfiguration
public static class TestConfig {
@Bean
BuildProperties buildProperties() {
return new BuildProperties(new Properties());
}
}
或者,如果需要在多个测试类中进行此额外配置,则可以将其创建为单独的类并使用@Import(TestConfig.class).
Or you can create it as a separate class and use @Import(TestConfig.class) if you need this extra configuration in multiple test classes.
这篇关于@WebMvcTest找不到buildProperties的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!