【发布时间】:2017-07-18 15:39:03
【问题描述】:
Spring Boot 版本 1.5.4.RELEASE。
正常运行应用程序工作正常。
在运行单元测试时,缺少一些 bean,例如:
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in ...service.post.PostService required a bean named 'mongoTemplate' that could not be found.
Action:
Consider defining a bean named 'mongoTemplate' in your configuration.
我正在使用 MongoDB 存储库。我通过添加一个返回这个bean的配置类来解决这个问题。
之后我再次尝试执行单元测试,出现以下错误:
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in springfox.documentation.spring.data.rest.BasePathAwareServicesProvider required a bean of type 'org.springframework.data.rest.core.config.RepositoryRestConfiguration' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.data.rest.core.config.RepositoryRestConfiguration' in your configuration.
这是由 springfox swagger ui Rest 文档提出的。删除此应用程序依赖项时,测试成功完成。
我在这里错过了什么?在单元测试“环境”中无法找到或自动配置某些 bean。
更新
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class ApplicationTests {
@Test
public void contextLoads() {}
}
@RunWith(SpringRunner.class)
@WebMvcTest(value = ProfileController.class, secure = false)
public class ProfileControllerTest {
private MockMvc mockMvc;
@MockBean private ProfileService profileService;
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.standaloneSetup(new ProfileController(profileService)).build();
}
@Test
....
}
这是我目前拥有的唯一测试控制器。
【问题讨论】:
-
您似乎有不同的配置来启动应用程序和测试。您可以通过 git 分享您的应用程序吗?我需要检查您的配置,如果没有这些信息,我无法为您提供修复。仅建议检查您的配置(配置文件、带注释的上下文配置...)。
-
这是一个私人项目,但我并没有为测试或其他什么特殊配置。大多数是使用 Spring Boot 自动配置的。请参阅更新部分进行测试。
-
您必须使用 @SpringBootTest(classes = Application.class) 注释您的 ProfileControllerTest 类以加载测试的测试上下文。
-
谢谢,但请注意它不适用于 @WebMvcTest。
标签: java spring rest unit-testing