【问题标题】:How to use custom Spring scope with unit tests (SpringJUnit4ClassRunner)如何在单元测试中使用自定义 Spring 范围 (SpringJUnit4ClassRunner)
【发布时间】:2014-09-17 10:06:23
【问题描述】:

我在我的 JUnit 测试中使用带有 @Configuration 注释的类中定义的 Spring 配置的 JUnit 测试。测试如下所示:

@ContextConfiguration(classes = MyConfiguration.class})
@RunWith(SpringJUnit4ClassRunner.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class SomeIntegrationTest {

    @Autowired
    private MyConfiguration myConfiguration;

    @Test
    public void someTest() throws Exception {
       myConfiguration.myBean();
    }
}

MyConfiguration,我想使用Spring作用域SimpleThreadScope

@Configuration
public class MyConfiguration {

    @Bean
    @Scope("thread")
    public MyBean myBean() {
        return new MyBean();
    }
}

但是,当我运行测试时,范围没有注册。我明白了

java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: java.lang.IllegalStateException: No Scope registered for scope 'thread'

我知道如何以编程方式注册自定义范围: context.getBeanFactory().registerScope("thread", new SimpleThreadScope());
我想避免使用 XML Spring 配置。

有什么办法,如何在单元测试中注册自定义范围?

【问题讨论】:

  • 你解决了这个问题吗?如果是,你是怎么解决的?
  • 嗨,我找到了一个非常优雅的解决方案,但我把它藏在某个地方,现在找不到它(代码已经被重构):)。让我再找一会儿。

标签: java spring junit junit4


【解决方案1】:

检查这个执行监听器:

public class WebContextTestExecutionListener extends
            AbstractTestExecutionListener {

        @Override
        public void prepareTestInstance(TestContext testContext) throws Exception {

            if (testContext.getApplicationContext() instanceof GenericApplicationContext) {
                GenericApplicationContext context = (GenericApplicationContext) testContext.getApplicationContext();
                ConfigurableListableBeanFactory beanFactory = context
                        .getBeanFactory();
                Scope requestScope = new SimpleThreadScope();
                beanFactory.registerScope("request", requestScope);
                Scope sessionScope = new SimpleThreadScope();
                beanFactory.registerScope("session", sessionScope);
                Scope threadScope= new SimpleThreadScope();
                beanFactory.registerScope("thread", threadScope);
            }
        }
    }

在测试中你可以放这个

    @ContextConfiguration(classes = MyConfiguration.class})
    @RunWith(SpringJUnit4ClassRunner.class)
    @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
    @TestExecutionListeners( { WebContextTestExecutionListener.class})
    public class UserSpringIntegrationTest {

    @Autowired
    private UserBean userBean;

    //All the test methods
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    • 2015-02-16
    • 1970-01-01
    相关资源
    最近更新 更多