【问题标题】:How to autowired a property in Junit class before executing any test with @RunWith(SpringJUnit4ClassRunner.class)如何在使用 @RunWith(SpringJUnit4ClassRunner.class) 执行任何测试之前自动装配 Junit 类中的属性
【发布时间】:2015-08-09 05:11:28
【问题描述】:

我正在尝试在使用 Before Class 注释执行任何 junit 测试之前执行代码(我在其中自动拧属性),但这里的问题是在应用程序上下文加载之前调用的带注释的方法,因此我得到了 null 值属性 (helloWorld)。

请参考相同的代码

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/SpringBeans.xml")
public class JunitTest {

    @Autowired
    private static HelloWorld helloWorld;

    @BeforeClass
    public static void methodBefore(){
        helloWorld.printHello();
        System.out.println("Before Class");
    }


    @Test
    public void method1(){
        System.out.println("In method 1");
    }

    @Test
    public void method2(){
        System.out.println("In method 2");
    }

    @Test
    public void method3(){
        System.out.println("In method 3");
    }

    @Test
    public void method4(){
        System.out.println("In method 4");
    }


    @AfterClass
    public static void methodAfter(){
        System.out.println("After Class");
    }

}

以同样的方式,我想在执行完所有 junit 测试后执行一些代码。

请建议我如何实现上述目标

【问题讨论】:

    标签: java spring junit


    【解决方案1】:

    您不应该在自动装配字段上使用静态。在这里查看更多:Can you use @Autowired with static fields? 从 HelloWorld 中删除静态,你应该没问题

    【讨论】:

      【解决方案2】:

      您无法自动关联静态字段 - 只需从 helloWorld 字段中删除静态修饰符即可。

      现在的问题是@BeforeClass 注解只能放在静态方法上。您必须将此方法替换为 Spring TestExecutionListener.beforeTestClass(TestContext) 方法

      根据您的要求,您可以使用现有的侦听器,例如 TransactionalTestExecutionListener,它可以在事务开始之前调用您的方法,例如

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-19
        • 2012-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多