복붙노트

[SPRING] 단위 테스트에서 Autowired Bean 재정의

SPRING

단위 테스트에서 Autowired Bean 재정의

특정 단위 테스트에서 autowired bean을 쉽게 오버라이드 할 수있는 간단한 방법이 있습니까? 컴파일 클래스에는 모든 유형의 빈이 하나만 있으므로이 경우에는 자동 와이어 링에 문제가 없습니다. 테스트 클래스에는 추가 모의가 포함됩니다. 단위 테스트를 실행할 때 기본적으로 말하는 추가 구성을 지정하고 싶습니다.이 사용 테스트를 실행하는 동안 표준 빈 대신이 모의를 사용합니다.

프로필은 내가 필요로하는 것에 조금 과장된 것처럼 보입니다. 다른 단위 테스트가 다른 mock을 가질 수 있으므로 기본 애노테이션으로 달성 할 수 있을지 확신 할 수 없습니다.

해결법

  1. ==============================

    1.테스트에서 다른 bean을 제공하고 싶다면 스프링 프로파일이나 mockito를 사용할 필요가 없다고 생각합니다.

    테스트에서 다른 bean을 제공하고 싶다면 스프링 프로파일이나 mockito를 사용할 필요가 없다고 생각합니다.

    다음을 수행하십시오.

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(classes = { TestConfig.class })
    public class MyTest
    {
        @Configuration
        @Import(Application.class) // the actual configuration
        public static class TestConfig
        {
            @Bean
            public IMyService myService()
            {
                return new MockedMyService();
            }
        }
    
        @Test
        public void test()
        {
            ....
        }
    }
    

    참고 : 봄 부팅 1.3.2 / 봄 4.2.4 테스트

  2. ==============================

    2.Spring Boot 1.4에는 다음과 같은 간단한 방법이있다.

    Spring Boot 1.4에는 다음과 같은 간단한 방법이있다.

    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = { MyApplication.class })
    public class MyTests {
        @MockBean
        private MyBeanClass myTestBean;
    
        @Before
        public void setup() {
             ...
             when(myTestBean.doSomething()).thenReturn(someResult);
        }
    
        @Test
        public void test() {
             // MyBeanClass bean is replaced with myTestBean in the ApplicationContext here
        }
    }
    
  3. ==============================

    3.나는 비슷한 문제를 겪었고 믹스로 해결했다. 그리고 나는 이것을 더 유용하고 재사용 할 수있는 것으로 생각한다. 테스트 용 스프링 프로파일과 매우 간단한 방법으로 조롱하려는 빈을 재정의하는 config 클래스를 만들었습니다.

    나는 비슷한 문제를 겪었고 믹스로 해결했다. 그리고 나는 이것을 더 유용하고 재사용 할 수있는 것으로 생각한다. 테스트 용 스프링 프로파일과 매우 간단한 방법으로 조롱하려는 빈을 재정의하는 config 클래스를 만들었습니다.

    @Profile("test")
    @Configuration
    @Import(ApplicationConfiguration.class)
    public class ConfigurationTests {
    
        @MockBean
        private Producer kafkaProducer;
    
        @MockBean
        private SlackNotifier slackNotifier;
    
    }
    

    그렇게함으로써 나는 그 모의 콩을 불러 들이고 그들을 검증하기 위해 모키토를 사용할 수있다. 주요 이점은 모든 테스트가 테스트 당 하나도 변경하지 않고 모의 콩을 완벽하게 얻을 수 있다는 것입니다. 테스트 대상 :

  4. ==============================

    4.다른 컨텍스트에서 어떤 종류의 bean을 사용하고 싶은지 봄 프로파일을 사용해야합니다.

    다른 컨텍스트에서 어떤 종류의 bean을 사용하고 싶은지 봄 프로파일을 사용해야합니다.

    http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html

  5. ==============================

    5.mats.nowak이 주석을 달았으므로 @ContextConfiguration이 유용합니다.

    mats.nowak이 주석을 달았으므로 @ContextConfiguration이 유용합니다.

    부모 테스트 클래스가 다음과 같다고 가정 해보십시오.

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = {"classpath:spring/some-dao-stuff.xml"
        ,"classpath:spring/some-rest-stuff.xml"
        ,"classpath:spring/some-common-stuff.xml"
        ,"classpath:spring/some-aop-stuff.xml"
        ,"classpath:spring/some-logging-stuff.xml"
        ,"classpath:spring/some-services-etc.xml"
    })
    public class MyCompaniesBigTestSpringConfig {
    ...
    

    하위 테스트 클래스 만들기 :

    package x.y.z;
    @ContextConfiguration
    public class MyOneOffTest extends MyCompaniesBigTestSpringConfig {
    ...
    

    src / test / resources / x / y / z / MyOneOffTest-context.xml에 넣는다.

    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
                               http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                               http://www.springframework.org/schema/context
                               http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
    
        <bean id="widgetsService" class="com.mycompany.mydept.myservice.WidgetsService" primary="true" />
    
    </beans>
    

    widgetsService 빈은 기본 config xml (또는 Java config)에 정의 된 bean을 대체 (대신 사용)합니다. 상속 된 위치보기 또한 기본 -context.xml 파일을 유의하십시오. 여기에 그 예가 있습니다. 업데이트 : 기본 = "true"를 추가해야했습니다. 분명히 필요합니다.

  6. from https://stackoverflow.com/questions/28605833/overriding-an-autowired-bean-in-unit-tests by cc-by-sa and MIT license