JUnit Rule + Java 8 Repeatable Annotations == Clean Tests

Last couple of months I am spending most of my free time writing Docker Java REST API client using RxJava and OkHttp. I have been following TDD for developing this API. Some of the test cases in RxDockerClientTest have to first create a docker container and then they perform other operations. For example, shouldStartCreatedContainer test case will test that API can start a created container. Similarly, there are test cases that need a container. One common solution to achieve this is to use @Before setUp and @After tearDown methods that take care of creating a container before test case is executed and removing the container after test execution. The problem with this solution is that container will be created for every test case in the test class. I only wanted to create a container for test cases that need it. Continue reading “JUnit Rule + Java 8 Repeatable Annotations == Clean Tests”

How to programmatically get process id of a Java process

This is how you can get process id of a Java process.

import java.lang.management.ManagementFactory;

public class JavaProcessId {

    public static void main(String[] args) {
        String vmName = ManagementFactory.getRuntimeMXBean().getName();
        int p = vmName.indexOf("@");
        String pid = vmName.substring(0, p);
        System.out.println(pid);
    }
}