【发布时间】:2020-01-25 22:07:55
【问题描述】:
我已经从 Spring Boot 1.5 升级到 Spring Boot 2.1.8。我有一些测试有效,但现在失败了。 我还在 2.9 版本中使用了 maven-surefire 插件,它工作正常,但我也将它升级到 2.22.0,如果这很重要的话。
@ExtendWith(SpringExtension.class)
@WebMvcTest(value = ElementController.class, secure = false)
@ContextConfiguration(classes = TestSite1Config.class)
public class ElementControllerSite1IT {
@Autowired
protected MockMvc mvc;
@MockBean
ElementService elementService;
@BeforeEach
public void setup() {
when(elementService.getElementTable( ... )) //skipping args for brevity
.thenReturn(new ElementTable());
}
@Configuration
public static class TestSite1Config {
@Bean
@Autowired
public ElementController elementController(final ElementService elementService) {
return new ElementController(elementService, new ElementControllerProperties(DeploymentLocation.SITE1));
}
@Test
public void failSite1ValidationWithoutId() throws Exception {
ElementParameters params = getParams(false);
mvc.perform(post("/element")
.contentType(JSON)
.andExpect(status().isBadRequest());
}
//more tests, but doesn't matter.
}
还有一个类似上面的类,但是将 Site1 替换为 Site2。
还有一个 ElementController & Service 类。
我得到了这个例外:
Caused by BeanDefinitionOverrideException: Invalid bean definition with name 'elementController' defined in class path resource [ui/v2/web/ElementControllerSite1IT$TestSite1Config.class]: Cannot register bean definition [Root bean: class [null]; ... defined in class path resource [ui/v2/web/ElementControllerSite1ITConfig.class] for bean 'elementController': There is already [Generic bean: class [ui.v2.web.ElementController]; .. defined in file [...ui/v2/web/ElementController.class]] bound.
我没有编写测试,它是我继承的代码,在我刚刚开始使用的代码库中。
【问题讨论】:
-
一开始就应该运行失败。删除
TestSite1Config, or at least remove the controller and only return theElementControllerProperties. Spring will take care of injecting the right properties in theElementController`,这就是@WebMvcTest中的ElementController。 -
为什么会失败?之前,它会自动覆盖 elementController bean(用于真实类),并使用此处创建的模拟对象。你能解释一下,或者给我一个链接到可能会阐明这一点的东西吗?我尝试删除 TestSite1Config 并且情况更糟。 ContextConfiguration 注释中会包含什么内容?
-
正如我在最初的评论中提到的,您应该只使用
ElementControllerProperties进行配置。 Spring 测试部分将负责创建ElementController,因为这是@WebMvcTest负责的。 -
我还是有点困惑。有一些东西是“配置”。你是说我的 TestSite1Config 应该只返回 ElementControllerProperties 吗?所以:
<code> @Configuration public static class TestSite1Config { @Bean public ElementControllerProperties elementControllerProperties() { return new ElementControllerProperties(DeploymentLocation.SITE1); } </code>这样做,在我的测试中,无论我扔给它什么,我都会得到 404,这至少意味着它正在连接一些东西?为什么这不像代码那样格式化?对不起 =( -
这就是它应该返回的内容。这与模拟服务一起应该足以创建
ElementController。虽然 404 很奇怪,但你能分享一下日志吗?
标签: spring spring-boot testing