如何在测试中也自动连接 ErrorAttributes?

How to get ErrorAttributes autowired also in tests?

这可能是非常基本的,但我是 Spring Boot 的新手(以及 Spring 一般的许多方面)并且 the documentation 没有直接回答这个问题。

设置

使用最新的 Spring Boot (1.2.1),我进行了一些集成测试,其中 Spring 被加载并且依赖项很好地自动装配(设置它非常简单)。

基础 class 测试:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public abstract class IntegrationTest {

}

主要的 Application class 与带有 SpringApplication.run() 和这些注释的主要方法相比没有太多:

@ComponentScan
@EnableAutoConfiguration
@EnableScheduling

示例测试:

public class UserServiceTest extends IntegrationTest {    
    @Autowired
    UserService userService;

    @Test
    public void testSomething() throws Exception {
        // Use UserService; make assertions
    }    
}

对于必要的依赖,我只有 spring-boot-starter-test:

<!-- Typical Spring Boot test dependencies: Spring Test, JUnit, Hamcrest, Mockito -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

问题

我创建了一个自定义 ErrorController along these lines, where I define an @Autowired ErrorAttributes field. See the CustomErrorController source code

在此之后,Spring 集成测试停止工作:

java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: 
    No qualifying bean of type [org.springframework.boot.autoconfigure.web.ErrorAttributes] found for dependency: 
    expected at least 1 bean which qualifies as autowire candidate for this dependency. 
    Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

问题

什么是最简单、在测试中也注入 ErrorAttributes bean 的最干净的方法?

我应该创建单独的 Application 用于测试,使用某种模拟的 ErrorAttributes bean,还是有更简单的方法?我是否缺少一些与 web/controller 测试相关的助手或依赖项?

@WebIntegrationTest

注释您的测试基础 class 或单个测试用例 classes

这里提到了:

http://docs.spring.io/spring-boot/docs/1.2.1.RELEASE/reference/htmlsingle/#boot-features-testing-spring-boot-applications

您可以使用 @WebAppConfiguration 注释测试 class 以指示 Spring 的测试框架创建 Web 应用程序上下文(这足以自动装配 ErrorAttributes)无需实际启动嵌入式容器。

以下代码对我有用Spring带注释的启动

@RunWith(SpringJUnit4ClassRunner.class)

@SpringApplicationConfiguration(classes =Application.class)

@WebIntegrationTest(randomPort=true)

@ContextConfiguration(classes = Application.class)


public class MyRepositoryIntegrationTests  {

    @Autowired
    private IMyRepository myRepository;



       @Test
       public void testSalutationMessage() {
          System.out.println("Inside testSalutationMessage()"+my.findAll());

          //assertEquals(message,message);
       }

}