如何在加载类之前绑定系统属性

时间:2018-06-18 22:17:52

标签: spring junit decorator system-properties junit-runner

我正在尝试模拟工厂的实现。实现是通过系统属性定义的。因此,为了模拟实现,我需要将我的模拟实现设置为系统属性。

此外,通常在加载任何类之前定义实现。所以,我不能使用mockito或不能使用@BeforeClass来设置我的属性。我正在寻找任何可以在加载类之前设置系统属性的JUnit $或Spring注释。

所以,我已经定义了自己的装饰器类,并使用JUnit4的@RunWith注释来装饰我的类到我的测试类。

SystemPropertyDecorator .java

public class SystemPropertyDecorator extends Decorator
{
   public SystemPropertyDecorator(Class<?> testClass)
   {
      super(testClass);
   }

   @Override
   public void run(Description description, Chain chain)
   {
       System.setProperty("com.media.util.ImageFactory",
        "com.sample.MockImageFactory");
       chain.proceed();
   }
}

将此用于我的测试类,如下所示:

TestClass.java

@RunWith(DecoratedTestRunner.class)
@DecoratedTestRunner.DecoratorClasses(SystemPropertyDecorator.class)
@ContextHierarchy(@ContextConfiguration("/spring/tests/MyDocument/setup.xml"))
public class TestClass extends BaseTest
{
    ...
}

通过这种方式,我能够根据需要设置系统属性,但问题是我添加的自定义装饰器覆盖了我的父类装饰器。

我的父类看起来像这样:

BaseTest.java

@SuppressWarnings("deprecation")
@RunWith(EnterpriseClientSpringJUnit4ClassRunner.class)
@ContextConfiguration("/spring/environment/environment.xml")
public abstract class BaseTest
{
     ...
}

因此,@ RunWith(EnterpriseClientSpringJUnit4ClassRunner.class)被我的子类@RunWith(DecoratedTestRunner.class)覆盖。我做了一些研究,发现我们不能对同一个类使用多个@RunWith注释。我无法将我的模拟代码添加到EnterpriseClientSpringJUnit4ClassRunner.class,因为我的代码不是独立的,并且使用EnterpriseClientSpringJUnit4ClassRunner的任何人都会受到我的模拟的影响。

所以,

  1. 我需要找到一种在类加载之前设置系统属性的方法(使用spring的注释或Junit的注释)或
  2. 我需要找到一种方法来同时使用装饰器。我可以使用@RunWith(DecoratedTestRunner.class) 在我的测试类中的@ DecoratedTestRunner.DecoratorClasses(SystemPropertyDecorator.class),然后将EnterpriseClientSpringJUnit4ClassRunner添加到我的自定义装饰器类中的跑步者列表中? 请告诉我。

0 个答案:

没有答案