spring - 使用 Autowiring 的 MockHttpServletRequest 进行的多次测试不起作用?

标签 spring testng spring-test

我在一些 Spring 测试中使用了 @Autowired MockHttpServletRequest。 TestNG用作测试框架。如果我在类里面只有一种测试方法,那么效果很好。但是,如果有多个测试方法,则只有第一个运行测试使用我的 MockHttpServletRequest。让我用一个例子来说明:

@WebAppConfiguration
@ContextConfiguration({"classpath:applicationContext.xml"})
public class FooTest extends AbstractTestNGSpringContextTests {

    @Autowired
    private MockHttpServletRequest servletRequest;

    @Test
    public void test1() {
        assertEquals(((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(), servletRequest);
    }

    @Test
    public void test2() {
        assertEquals(((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(), servletRequest);
    }

}

在此示例中,test1() 通过,但 test2() 失败!如果单独运行测试方法,它们都会通过。如果一起运行,为什么一项测试会失败?

我尝试深入研究代码,在测试方法运行后似乎有某种请求属性的重置,但我没有找到将其关闭的方法。我的 Spring 版本是 3.2.8.RELEASE。

最佳答案

更新:此问题已在 Spring Framework 3.2.9、4.0.4 和 4.1 中修复。请参阅SPR-11626了解详情。


好吧,我的 friend ...您在 Spring TestContext Framework 中发现了一个错误。

出现此行为的原因是 ServletTestExecutionListener 在每个测试方法之后重置请求属性,但 DependencyInjectionTestExecutionListener 不会在每个测试方法之前重新注入(inject)依赖项(默认情况下) 。当执行第二个测试方法时,servletRequest字段仍然引用为前一个测试方法创建的MockHttpServletRequest;而 ServletTestExecutionListener 为每个测试方法创建一个新的 MockHttpServletRequest 实例,并将其设置在请求属性中。因此,注入(inject)的请求和存储在 RequestContextHolder 中的请求仅对于 TestNG 中执行的第一个测试方法是相同的。

由于我是这段代码的作者,我必须亲自道歉,但是......我会确保它尽快得到修复。请参阅SPR-11626有关修复状态的详细信息。 ;)

注意:此错误仅适用于 TestNG 测试;这不适用于 JUnit 测试。

作为解决方法,您可以使用 @DirtiesContext 注释受影响的测试方法(或使用 @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) 注释您的测试类) 。这将使您的测试按照您的预期通过。

使用@DirtiesContext将使Spring在每个测试方法之后关闭您的测试ApplicationContext,这可能会对您的测试速度产生负面影响;但是,从 Spring 3.2.8 和 4.0.3 开始,这是唯一的非自定义解决方案。

话虽如此,以下是一种更有效的解决方法。只需在您的项目中定义此自定义 TestExecutionListener:

public class AlwaysReinjectDependenciesTestExecutionListener extends AbstractTestExecutionListener {

    public void afterTestMethod(TestContext testContext) throws Exception {
        testContext.setAttribute(DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE, Boolean.TRUE);
    }

}

然后像这样注释你的测试类:

@TestExecutionListeners(AlwaysReinjectDependenciesTestExecutionListener.class)

这应该可以解决任何问题让您的测试套件快速运行。

问候,

山姆

关于spring - 使用 Autowiring 的 MockHttpServletRequest 进行的多次测试不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22712325/

相关文章:

java - Postgres 的搜索路径不适用于 Spring/DBCP 数据源

java - Spring Boot @RestController 使用属性启用/禁用方法

java - 使用外部网络服务时的测试策略

java - Gradle + TestNG 仅运行指定组

java - "Failed to load ApplicationContext"使用@ContextConfiguration( "/applicationContext.xml") 和 Maven 结构

spring - 在不创建 Web 套接字消息代理 Spring 4 的情况下使用 SimpMessagingTemplate

java - 批处理在 Spring+Hibernate+JPA 中内存不足

java - 测试。如何正确处理这个异常

json - 如何强制`.andExpect(jsonPath()`)返回Long/long而不是int以获取 jackson 解析器的int数

grails - 在带有 Grails 2.1.1 的 Groovy 1.8 中缺少依赖项 spring-test-3.1.2.RELEASE.zip