javaeclipsejunitjvm

Start Java main in another process (VM)


I have a server client project and for testing purposes I want to start the server in a whole new process. The problem is, I have just a main() method in project, no jar. So my guess would be something like

Runtime.getRuntime().exec("javac MyServer.java");
Runtime.getRuntime().exec("java class MyServer");

But I am really not sure about it and also I don't exactly like the need to start javac for each test case.

How should I proceed?

EDIT

I want to start the process in the @Before method and destroy it in @After. It has to run automatically, so manual turning on the server is not an option. What I was looking for is a way to eliminate compilation of the server class. But now I guess there is no other way.


Solution

  • Take a look at JUnit, what I think you want to do is run a series of tests against your client, with a server running. You can accomplish this by writing a JUnit test which makes use of the @Before annotation to run a setup method before each test. For example:

    import org.junit.Before
    
    public class TestClient {
        private static final int port = 20000 + new Random().nextInt(10000);
        private MyServer server;
    
        @Before
        public void setup() {
            // setup server
            server = new MyServer(port);
            server.start();
        }
    
        @Test
        public void testX() {
            // test x
        }
    
        @Test
        public void testY() {
            // test y
        }
    }