programing

TestNG를 사용한 스프링 종속성 주입

firstcheck 2021. 1. 14. 08:31
반응형

TestNG를 사용한 스프링 종속성 주입


Spring은 JUnit을 매우 잘 지원합니다. RunWithContextConfiguration주석을 사용하면 매우 직관적으로 보입니다.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:dao-context.xml")

이 테스트는 Eclipse와 Maven 모두에서 올바르게 실행할 수 있습니다. TestNG와 비슷한 것이 있는지 궁금합니다. 이 "차세대"프레임 워크로의 전환을 고려하고 있지만 Spring 테스트와 일치하는 항목을 찾지 못했습니다.


TestNG에서도 작동합니다. 귀하의 테스트 클래스는 필요가 확장 다음의 클래스 중 하나를


다음은 나를 위해 일한 예입니다.

import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.Test;

@Test
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class TestValidation extends AbstractTestNGSpringContextTests {

    public void testNullParamValidation() {
        // Testing code goes here!
    }
}

Spring과 TestNG는 함께 잘 작동하지만 몇 가지 알아야 할 사항이 있습니다. AbstractTestNGSpringContextTests를 서브 클래 싱하는 것 외에도 표준 TestNG 설정 / 해체 주석과 상호 작용하는 방법을 알고 있어야합니다.

TestNG에는 4 가지 수준의 설정이 있습니다.

  • BeforeSuite
  • BeforeTest
  • BeforeClass
  • BeforeMethod

예상대로 정확히 발생합니다 (자체 문서화 API의 훌륭한 예). 이들은 모두 "dependsOnMethods"라는 선택적 값을 가지며, 같은 수준에있는 메서드의 이름 또는 이름 인 String 또는 String []을 사용할 수 있습니다.

AbstractTestNGSpringContextTests 클래스에는 springTestContextPrepareTestInstance라는 BeforeClass 어노테이션이있는 메소드가 있습니다.이 메소드는 자동 연결 클래스를 사용하는 경우 종속되도록 설정 메소드를 설정해야합니다. 메서드의 경우 자동 연결에 대해 걱정할 필요가 없습니다. 클래스 메서드 이전에 테스트 클래스가 설정 될 때 발생하기 때문입니다.

이것은 BeforeSuite로 주석이 달린 메소드에서 autowired 클래스를 사용하는 방법에 대한 질문을 남깁니다. springTestContextPrepareTestInstance를 수동으로 호출하여이 작업을 수행 할 수 있습니다. 기본적으로이를 수행하도록 설정되어 있지는 않지만 여러 번 성공적으로 수행했습니다.

따라서 설명하기 위해 Arup 예제의 수정 된 버전을 살펴 보겠습니다.

import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.Test;

@Test
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class TestValidation extends AbstractTestNGSpringContextTests {

    @Autowired
    private IAutowiredService autowiredService;

    @BeforeClass(dependsOnMethods={"springTestContextPrepareTestInstance"})
    public void setupParamValidation(){
        // Test class setup code with autowired classes goes here
    }

    @Test
    public void testNullParamValidation() {
        // Testing code goes here!
    }
}

참조 URL : https://stackoverflow.com/questions/2608528/spring-dependency-injection-with-testng

반응형