Issue
I'm working with a declarative Jenkins pipeline that runs some tests which make use of JUnit 4. In the tests there are @After
methods where test cleanup occurs. When a pipeline is aborted during a test I've confirmed that the @After
methods are never executed (confirmed using log statements in the @After
methods and checking the Jenkins console log).
This leaves test data (e.g. users that the tests use) in a bad state and cause later tests (and pipeline builds) to fail, so it's an issue.
The pipeline is aborted via the Jenkins UI "stop" button, or through the pipeline hitting a timeout for that stage. In both cases the pipeline exits with code 143, which is a SIGTERM
.
How can I ensure that JUnit 4.x @After
methods are executed when a declarative Jenkins pipeline is aborted?
Solution
I have a workaround that you could use to solve the issue. Create two classes. TestClass and AfterClass. In the AfterClass, you will have to keep one test method so that after will get triggered. Now, In test execution step of declarative pipeline, you can execute
mvn clean test -PTest
and in the post always of declarative pipeline script, you can execute below maven command
mvn clean test -PCleanup
TestClass:
import org.junit.Test;
public class TestClass
{
@Test
public void testClass()
{
System.out.println("Test");
}
}
AfterClass:
@Test
public void beforeCleanUp()
{
System.out.println("Before Cleanup");
}
@After
public void after()
{
System.out.println("After");
}
POM.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>stackovrflw-62492859</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>Test</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<test>com.test.junit.classes.TestClass</test>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>Cleanup</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<test>com.test.junit.classes.AfterClass</test>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
Note: This is not the actual solution as I do not have much experience on JUnit. But you could use this workaround, if you do not get any proper solution. I will be also trying to find proper solution for you
Answered By - UnknownBeast
Answer Checked By - David Goodson (JavaFixing Volunteer)