예제 #1
0
  /**
   * 初始化当前测试类用到的spring application context对象
   *
   * @param testedObject
   * @param contextFactory
   * @return does initial spring context successfully
   */
  @SuppressWarnings("rawtypes")
  public static JTesterBeanFactory initSpringContext(
      Class testClazz, ApplicationContextFactory contextFactory) {
    JTesterBeanFactory beanFactory = (JTesterBeanFactory) TestedObject.getSpringBeanFactory();
    if (beanFactory != null) {
      return beanFactory;
    }
    SpringApplicationContext annotation =
        AnnotationUtils.getClassLevelAnnotation(SpringApplicationContext.class, testClazz);
    if (annotation == null) {
      return null;
    }

    long startTime = System.currentTimeMillis();

    String[] locations = annotation.value();
    boolean ignoreNoSuchBean = annotation.ignoreNoSuchBean();
    JTesterSpringContext context =
        contextFactory.createApplicationContext(Arrays.asList(locations), ignoreNoSuchBean);

    context.refresh();
    long duration = System.currentTimeMillis() - startTime;
    JTesterLogger.warn(
        String.format(
            "take %d ms to init spring context for test obejct[%s]",
            duration, testClazz.getName()));

    beanFactory = context.getJTesterBeanFactory();
    TestedObject.setSpringContext(beanFactory);
    return beanFactory;
  }
예제 #2
0
 /**
  * 释放测试类的spring容器
  *
  * @param springContext AbstractApplicationContext实例,这里定义为Object是方便其它模块脱离spring依赖
  */
 public static void closeSpringContext(Object beanFactory) {
   if (beanFactory == null) {
     return;
   }
   if (beanFactory instanceof JTesterBeanFactory) {
     ((JTesterBeanFactory) beanFactory).destroySingletons();
     JTesterLogger.warn("close spring context for class:" + TestedObject.currTestedClazzName());
   } else {
     String error =
         String.format(
             "there must be something error, the type[%s] object isn't a spring context.",
             beanFactory.getClass().getName());
     throw new RuntimeException(error);
   }
 }