How to create before / after class methods for JUnit 4 using Spring 3 framework

When I wrote a JUnit class for testing inprocess FTP server, I'd like to startup the server when the class initiates and shutdown when the class is being destroyed.

I saw it is pretty easy with JUnit 4 annotations to use the @BeforeClass and @AfterClass above the startup and shutdown methods, and insert the required actions inside them.

The problem is those methods should be defined as static, and when using Spring resource like ftp server it can't be defined as a static variable because the Ioc is happening during the Spring life cycle. Here is a code segment describes the problematic:

// The resource can't be static.
@Resource
private static FtpServer ftpServer;

@BeforeClass
public static void beforeTestClass() throws Exception {
   ftpServer.start();
}
@AfterClass
public static void afterTestClass() throws Exception {
   ftpServer.stop();
}

To overcome this situation I create TestExecutionListener which is a listener triggered by the Spring life cycle and enables us to add our custom code during the Spring loading process. In the case above I implement the methods beforeTestClass and afterTestClass to achieve my goal. Here is a code segment with the implementation:

public class FtpTestExecutionListener extends AbstractTestExecutionListener {
   @Override
   public void beforeTestClass(TestContext testContext)
   throws Exception {
      FtpServer ftpServer = (FtpServer)
      testContext.getApplicationContext().getBean(ftpServer);
      ftpServer.start();
   }
   @Override
   public void afterTestClass(TestContext testContext)
   throws Exception {
      FtpServer ftpServer = (FtpServer)
      testContext.getApplicationContext().getBean(ftpServer);
      ftpServer.stop();
   }
}

Finally we also need to register our listener by adding annotation to the JUnit class:

@TestExecutionListeners(listeners = FtpTestExecutionListener.class)

 

Thank you for your interest!

We will contact you as soon as possible.

Send us a message

Oops, something went wrong
Please try again or contact us by email at info@tikalk.com