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

Java 如何在单元测试中使用自定义Spring作用域(SpringJUnit4ClassRunner),java,spring,junit,junit4,Java,Spring,Junit,Junit4,我正在使用JUnit测试,在JUnit测试中用@configuration注释的类中定义了Spring配置。测试如下所示: @ContextConfiguration(classes = MyConfiguration.class}) @RunWith(SpringJUnit4ClassRunner.class) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) public class So

我正在使用JUnit测试,在JUnit测试中用
@configuration
注释的类中定义了Spring配置。测试如下所示:

@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(“线程”,新的SimpleThreadScope())
我希望避免使用XMLSpring配置


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

检查此执行侦听器:

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
    }

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