정적 @BeforeClass에서 필드를 자동 배선하는 방법은 무엇입니까?
@RunWith(SpringJUnit4ClassRunner.class)
public void ITest {
@Autowired
private EntityRepository dao;
@BeforeClass
public static void init() {
dao.save(initialEntity); //not possible as field is not static
}
}
정적 init 클래스에서 서비스를 이미 주입하려면 어떻게 해야 합니까?
Junit 5를 사용하면 이 작업을 수행할 수 있습니다(@BeforeClass 대신 @BeforeAll).
public void ITest {
@Autowired
private EntityRepository dao;
@BeforeAll
public static void init(@Autowired EntityRepository dao) {
dao.save(initialEntity); //possible now as autowired function parameter is used
}
}
필드를 떠난다는 것은 다른 테스트에서 사용할 수 있음을 의미합니다.
이 작업을 수행하기 위해 사용한 한 가지 해결 방법은@Before
각 테스트 케이스에 대해 실행되는 것을 건너뛰는 플래그와 함께.
@RunWith(SpringJUnit4ClassRunner.class)
public class BaseTest {
@Autowired
private Service1 service1;
@Autowired
private Service2 service2;
private static boolean dataLoaded = false;
@Before
public void setUp() throws Exception {
if (!dataLoaded) {
service1.something();
service2.somethingElse();
dataLoaded = true;
}
}
}
Spring 2.x 버전용 UPD.
스프링 2.x는 새로운 기능을 지원합니다.SpringExtension
Junit 5 Jupiter에게 당신이 해야 할 일은 다음과 같습니다.
테스트 클래스를 다음과 같이 선언합니다.
@ExtendWith(SpringExtension.class)
주사를 놓습니다.
@BeforeAll
(대체 대상@BeforeClass
Junit 5)에서 콩과 함께
예를 들어,
@ExtendWith(SpringExtension.class)
...
public void ITest {
@BeforeAll
public static void init(@Autowired EntityRepository dao) {
dao.save(initialEntity);
}
}
JUNit 5 Jupiter를 Spring 2.x로 올바르게 구성했다고 가정합니다.
자세한 내용은 https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#testcontext-junit-jupiter-extension 에서 확인할 수 있습니다.
테스트 전에 DB를 채우려고 하는 것 같습니다.
다음 두 가지 옵션을 사용해 보겠습니다.
- 초기 스크립트를 sql 파일로 추출할 수 있는 경우(repository bean을 사용하지 않고 사용할 수 있는 옵션인 경우) 이 방법을 사용하여 다음과 같이 테스트에 주석을 달 수 있습니다.
@Sql
- DbUnit을 탐색할 수 있으며 테스트 전 DB를 채울 수 있도록 도와주는 스프링 DbUnit 커넥터 링크가 여기에 있습니다.스프링 테스트 프레임워크와 dbunit 간의 통합을 위한 github 링크입니다.그렇게 한 후에 당신은.
@DatabaseSetup
그리고.@DatabaseTearDown
당신이 필요로 하는 DB에서 무엇을 할 것인가요?
저는 이것이 고정된 상태에서 콩을 주입하는 방법에 대한 답이 아니라는 것을 알고 있습니다.@BeforeClass
하지만 폼코드는 당신의 문제를 해결하고 있는것 같습니다.
업데이트: 저는 최근 프로젝트에서 같은 문제에 부딪혀 이 기사를 발견하여 도움이 되었고, 이러한 유형의 문제를 다루는 우아한 방법이라고 생각합니다.연장 가능합니다.SpringJUnit4ClassRunner
모든 정의된 콩으로 인스턴스 레벨 설정을 수행할 수 있는 청취자와 함께.
이 질문에 답하려면 Spring 2.x 버전을 요약해야 합니다.
만약 당신이 당신의 콩을 "자동 배선"하고 싶다면,@BeforeTest
당신이 사용할 수 있는 클래스.ApplicationContext
인터페이스.예를 들어 보겠습니다.
@BeforeClass
public static void init() {
ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
EntityRepository dao2 = (EntityRepository) context.getBean("dao");
List<EntityRepository> all = dao2.getAll();
Assert.assertNotNull(all);
}
무슨 일이 일어나고 있습니까?ClassPathXmlApplicationContext
우리는 모든 콩을 인스턴스화하고 있습니다.application-context.xml
파일.
와 함께context.getBean()
지정된 콩을 읽습니다(콩의 이름과 일치해야 합니다!). 그런 다음 초기화에 사용할 수 있습니다.
콩에 다른 이름을 붙여야 합니다.dao2
노멀 "할 수 .!" " " " " " " " 할 " 에서 " 된 " " " " " " " " " 할 " " " " 에서 "
범위가 로, 이 되는 되는 이 로 AbstractTransactionalJUnit4SpringContextTests
할수다다수할을 사용하여 초기화를 수행할 수 있습니다.executeSqlScript(sqlResourcePath, continueOnError)
; 따라서 별도로 테스트해야 하는 클래스/클래스에 의존하지 않습니다.
테스트에 일부 DB 데이터를 사용하려는 경우 저장소를 조롱하고 @Before 해결 방법 Narain Mittal에서 설명하는 내용을 사용할 수도 있습니다.
@RunWith(SpringJUnit4ClassRunner.class)
public void ITest {
@MockBean
private EntityRepository dao;
@Before
public static void init() {
when(dao.save(any())).thenReturn(initialEntity);
}
}
언급URL : https://stackoverflow.com/questions/29340286/how-to-autowire-field-in-static-beforeclass
'programing' 카테고리의 다른 글
MariaDB의 CANCAT 키가 10.0에서 작동하지만 이후 버전은 작동하지 않는 테이블 (0) | 2023.09.09 |
---|---|
안드로이드:배열에서 프로그래밍 방식으로 스피너 생성 (0) | 2023.09.09 |
오류: int 이전의 식이 필요합니다. (0) | 2023.09.09 |
파일이 존재하는지 테스트하는 빠른 방법은 무엇입니까? (0) | 2023.09.09 |
MariaDB 10.2의 utf_8_span_ci colation이 제대로 작동합니까? (0) | 2023.09.04 |