【问题标题】:Spring session-scoped bean in TestNG test?TestNG测试中的Spring会话范围bean?
【发布时间】:2014-03-18 18:23:37
【问题描述】:

从 Spring 3.2 开始,您可以在测试中使用请求范围和会话范围的 bean,可以读取 in the Spring reference manual, section 11.3.5

例如:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({"classpath:applicationContext.xml"})
public class Test1
{
    @Autowired
    private MySessionBean state;

    @Test
    public void test() {
        System.out.println(state.toString());
    }
}

以上工作。但是,尝试将其调整为 TestNG:

@WebAppConfiguration
@ContextConfiguration({"classpath:applicationContext.xml"})
public class Test2 extends AbstractTestNGSpringContextTests
{
    @Autowired
    private MySessionBean state;

    @Test
    public void test() {
        System.out.println(state.toString());
    }
}

这会抛出异常:

java.lang.IllegalStateException:未找到线程绑定请求:是 您指的是实际 Web 请求之外的请求属性, 还是在原始接收线程之外处理请求?

我是在做错什么,还是使用仅受 JUnit 支持而不支持 TestNG 的会话范围 bean 进行测试?

【问题讨论】:

    标签: spring testng spring-test


    【解决方案1】:

    如果您不在 Spring Framework 3.2.7 或更高版本上,默认情况下这将不起作用。

    详情请见SPR-11340

    作为一种变通方法,您可以如下声明您的测试类

    @WebAppConfiguration
    @ContextConfiguration("/applicationContext.xml")
    @TestExecutionListeners({
      ServletTestExecutionListener.class,
      DependencyInjectionTestExecutionListener.class,
      DirtiesContextTestExecutionListener.class
    })
    public class Test2 extends AbstractTestNGSpringContextTests { /* ... */ }
    

    问候,

    山姆

    【讨论】:

    • 知道如何让它适用于有线模拟服务器吗?
    猜你喜欢
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    相关资源
    最近更新 更多