java - 如何在单元测试中使用自定义 Spring 作用域 (SpringJUnit4ClassRunner)

标签 java spring junit junit4

我在 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 配置。

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

最佳答案

检查这个执行监听器:

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
    }

关于java - 如何在单元测试中使用自定义 Spring 作用域 (SpringJUnit4ClassRunner),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25887688/

相关文章:

java - 从动态更新的 Application.properties 中读取

java - JUnit - 我应该将 null 分配给在 setUp 中实例化的 tearDown 中的资源吗?

Java访问数组等对象

java - cassandra.bat 在 0.7rc1 中抛出 java.io.IOException : rename failed of LocationInfo-e -1-Data. db

Java-Socket : Multiple Clients error

java - 在没有运行定位器的情况下启动 spring-data-gemfire

spring - PROPAGATION_NESTED vs PROPAGATION_ Spring 需要吗?

java - Jacoco 代理 - 无输出

java - 无法正确应用其余 Controller junit 测试

solr - JUnit、向后兼容性和 SOLR 测试