2014-09-17 2 views
2

JUnit 테스트에서 @Configuration으로 주석 된 클래스에 정의 된 스프링 구성으로 JUnit 테스트를 사용하고 있습니다. 시험은 다음과 같습니다 :하지만, 내가 테스트를 실행하면유닛 테스트 (SpringJUnit4ClassRunner)로 커스텀 스프링 스코프 사용하기

@Configuration 
public class MyConfiguration { 

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

는, 범위는 등록되지 않은 : MyConfiguration에서 나는 봄의 범위 SimpleThreadScope을 사용하고자하는

@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(); 
    } 
} 

. context.getBeanFactory().registerScope("thread", new SimpleThreadScope());
내가 XML의 Spring 설정을 사용하지 않도록하고 싶습니다 : 나는 사용자 지정 범위는 프로그래밍 방식으로 등록 할 수있는 방법을 알고

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

를 얻을.

방법이 있습니까? 단위 테스트에서 사용자 지정 범위를 등록하려면 어떻게해야합니까?

+0

당신이이 문제를 해결 한 넣을 수 있습니다? 그렇다면 어떻게 해결 했습니까? – Xstian

+0

안녕하세요, 꽤 우아한 솔루션을 찾았습니다. 그러나 어딘가에 숨겨두고 지금 찾을 수 없습니다 (코드가 리팩토링되었습니다. :). 좀 더 자세히 살펴 보도록하겠습니다. – Mifeet

답변

4

확인이 실행 청취자 : 테스트에서

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 
    } 
관련 문제