2012-07-03 2 views
52

배포 된 WAR의 XML Spring 구성을 확인하는 몇 가지 테스트를 작성하고 싶습니다. 불행히도 일부 빈은 일부 환경 변수 또는 시스템 특성이 설정되도록 요구합니다. @ContextConfiguration과 함께 편리한 테스트 스타일을 사용할 때 스프링 빈이 초기화되기 전에 어떻게 환경 변수를 설정할 수 있습니까?스프링 테스트에서 환경 변수 또는 시스템 속성을 설정하는 방법은 무엇입니까?

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = "classpath:whereever/context.xml") 
public class TestWarSpringContext { ... } 

주석이있는 응용 프로그램 컨텍스트를 구성하면 스프링 컨텍스트가 초기화되기 전에 내가 할 수있는 부분이 보이지 않습니다.

답변

75

당신은 static 초기화 시스템 속성을 초기화 할 수 있습니다 : 스프링 애플리케이션 컨텍스트가 초기화되기 전에

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = "classpath:whereever/context.xml") 
public class TestWarSpringContext { 

    static { 
     System.setProperty("myproperty", "foo"); 
    } 

} 

정적 초기화 코드가 실행됩니다.

+8

어리석은 me - 좋아, 그게 효과가있다. 더 나은 점은 아마도 시스템 프로퍼티를 설정하는 @ @ BeforeClass 메소드와이를 제거하기위한 @ @ AfterClass 메소드가 작동하고 멋지게 정리할 수 있다는 것입니다. (그래도 사용하지 않았다.) –

+1

@BeforeClass를 사용해 보았는데, 다른 속성이 테스트 인스턴스에 설정되기 전에 시스템 속성을 설정하는 데는 문제가 없었다. – wbdarby

+0

감사합니다. 정적 인 것은 작동하지 않지만 @BeforeClass로 작은 메소드가 작동했습니다! –

45

스프링 4.1부터는 올바른 방법은 @TestPropertySource 주석을 사용하는 것입니다. Spring docsJavadocs에서

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = "classpath:whereever/context.xml") 
@TestPropertySource(properties = {"myproperty = foo"}) 
public class TestWarSpringContext { 
    ...  
} 

참조 @TestPropertySource.

+1

이 주석은 또한 특성 파일 경로를 지원합니다. – MigDus

+2

테스트 중에 @TestPropertySource (properties = { "spring.cloud.config.label = feature/branch"})를 사용하여 Spring Cloud Config Client 레이블을 바꿀 수있다. –

+0

좋은 답변이지만, 슬프게도 나를 위해 작동하지 않았다. 봄 4.2.9, 속성은 항상 비어있었습니다. 정적 블록 만 작동했습니다 ... 시스템 속성 대신 응용 프로그램 속성에 대해 작업했습니다. – Gregor

4

하나 또한 시스템 프로퍼티 초기화 테스트 ApplicationContextInitializer를 사용할 수 있습니다

public class TestApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> 
{ 
    @Override 
    public void initialize(ConfigurableApplicationContext applicationContext) 
    { 
     System.setProperty("myproperty", "value"); 
    } 
} 

을하고 Spring 컨텍스트 설정 파일의 위치뿐만 아니라 테스트 클래스를 구성 :

@ContextConfiguration(initializers = TestApplicationContextInitializer.class, locations = "classpath:whereever/context.xml", ...) 
@RunWith(SpringJUnit4ClassRunner.class) 
public class SomeTest 
{ 
... 
} 

이를 모든 단위 테스트에 대해 특정 시스템 등록 정보를 설정해야한다면 양방향 코드 중복을 피할 수 있습니다. 당신이 당신의 변수는 모든 시험에 대해 유효하려면

0

, 당신은 (기본적으로 : src/test/resources)를 테스트 자원 디렉토리에 application.properties 파일을 가질 수 같은 것을 볼 것이다 :

MYPROPERTY=foo 

를이 다음 것이다 @TestPropertySource을 통한 정의 또는 유사한 방법을 사용하지 않는 한로드되고 사용됩니다. 속성이로드되는 정확한 순서는 Spring 설명서 장 24. Externalized Configuration에서 찾을 수 있습니다.

관련 문제