2

I am trying to execute a code (in which I am auto wring a property) before executing any junit test using Before Class annotation but here problem is that annotated method called before application context load due to this I get the null value in property (helloWorld).

Please refer code for the same

@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");
    }

}

In the same way I want to execute some code after executing all junit test.

please suggest how can I achieve above things

Rajeev
  • 519
  • 3
  • 13
  • 29

2 Answers2

0

you shouldn't use static on autowired field. see more here: Can you use @Autowired with static fields? remove the static from HelloWorld and you should be ok

Community
  • 1
  • 1
Nir Levy
  • 12,750
  • 3
  • 21
  • 38
0

You cannot autowire the static field - just remove the static modifier from helloWorld field.

Now the problem is that @BeforeClass annotation can be put on static methods only. You'll have to replace this method with Spring TestExecutionListener.beforeTestClass(TestContext) method

Depending on your requirements you might take on of the existing listeners like TransactionalTestExecutionListener which can call your methods say before the transaction is started, e.t.c.

bedrin
  • 4,458
  • 32
  • 53