2014-01-08 1 views
0

저는 처음부터 java-ee와 arquillian (일반적으로 유닛 테스트)을 사용하여 모험을 시작한다고 말합니다.유닛 @Startup @Singleton 빈에서 @PostConstruct 메소드를 테스트하십시오.

나는 wildfly 8.0.0CR1을 사용하고 있습니다.

기본 db의 초기화를 수행하는 @PostConstruct 메소드를 사용하여 간단한 @Singleton @Startup bean 인 클래스 (이 "초기화 Bean"이라고 부름)를 작성했습니다.

@Before 메서드 내에있는 단위 테스트는 모든 db의 테이블을 잘라내어 초기화 단계를 준비하는 단위 테스트입니다.

문제는 단위 테스트가 설정되기 전에 Initialization Bean @PostContruct 메서드가 호출되어 모든 데이터베이스 테이블을 잘라야하는 메서드가 실제로 Initialization Bean @PostContruct 메서드 후에 호출된다는 것입니다.

@Singleton@Startup 콩에서 @PostContruct 메서드를 올바르게 디버깅하려면 어떻게해야합니까?

나는 충분히 명확 해 졌으면 좋겠다. 그렇지 않으면 내일 진짜 코드를 게시 할 것이다. 미리 감사드립니다.

답변

2

init bean에 @javax.ejb.Singleton으로 주석을 붙였습니까?

동일한 문제가 발생했다면, init bean에 @javax.inject.Singleton이라는 주석을 달았습니다. 주석을 수정 한 후 @PostConstruct 메소드가 호출됩니다.

+0

안녕 @DuCh이 내 문제는 Arquillian를 사용하여 postContruct 방법 본체를 디버깅하는 방법에 대한 자세한이었다. 내'@ PostConstruct' 메소드가 정상적으로 작동했습니다. 내 문제는 주로 콩을 내 AS-7에 배치하고 코드를 테스트하기 전에 테이블을 잘라내는 것에 관한 것이 었습니다. 필자는'@ PostConstruct' 내부에서 실행되는 코드에 대한 테스트 유닛을 작성하고 모든 DB 테이블을 잘라내어 빈을 배치하는'@ Deployment' 메소드 내부에서 호출 된 정적 함수를 작성했습니다. 문안 인사 –

-1

한 가지 방법으로 문제를 해결할 수 있습니다. @PostConstruct 메소드를 사용하여 Bean 객체를 생성 할 때 Autowire를 사용해서는 안됩니다. Java 코드를 통해 Bean을 작성할 수 있습니다. 방법이 같은 테스트 클래스의

1 메이크업 : 테스트

private BeanFactory getTestBeanFactory() { 
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath*:<your test context>-test.xml"); 
    return applicationContext.getAutowireCapableBeanFactory(); 
} 

이이 코드 수행

// get your bean object 
YourBean yourBean = getTestBeanFactory().getBean(YourBean.class); 
// call manually a post construct method of your bean 
yourBean.<the post construct method of your bean>(); 
// do something with the yourBean 
... 

`의 작동 잘

행운을

0

리플렉션을 사용하여 @StartUp 클래스를 인스턴스화하고 각 테스트 c 전에 @PostConstruct 메소드를 호출 할 수 있습니다. 젊은 여자. 분명히 이것은 Spring에서 쉽게 할 수 있지만이 환경에서 Spring을 사용하지는 않습니다. 여기에 내가 그것을 어떻게의 예입니다

public class BaseTest { 
    @BeforeClass 
    public static void instantiateStartupClasses() throws InvocationTargetException, IllegalAccessException, InstantiationException { 
     Reflections reflections = new Reflections("com.company.project"); 
     //Find all classes annotated with Startup in a given package. 
     Set<Class<?>> classes = reflections.getTypesAnnotatedWith(Startup.class); 
     for(Class clazz : classes) { 
      if(clazz.isInterface()) continue; 
      //Instantiate the object 
      Object instantiatedClass = clazz.newInstance(); 
      //Find any PostConstruct methods on the class and invoke them using the instantiated object. 
      for(Method method : clazz.getDeclaredMethods()) { 
       if(method.isAnnotationPresent(PostConstruct.class)) { 
        //Invoke the post constructor method. 
        method.invoke(instantiatedClass); 
       } 
      } 
     } 
    } 
} 
관련 문제