Unit testing Java Threads

I have a main program that creates a Thread to do something.

The worker thread calls a long running service and uses some sort of callback function to notify about its response.

public class TestingThreads {
    public static void main(String[] args) {
        Thread workerThread = new Thread(new WorkerThread());
        workerThread.run();
    }

    public static class WorkerThread implements Runnable {
        private ConfigService service;

        @Override
        public void run() {

            Response response = new Response() {
                @Override
                public void onResponse(String result) {
                    //Do something on the response
                }
            };

            Request request = new Request();
            service.callSomething(request, response);

            //Wait for response before exiting this run loop
        }

    }

    public static abstract class Response {
        public abstract void onResponse(String result);
    }

    public static class Request {
    }

    public static class ConfigService {
        public void callSomething(Request request, Response response) {
            // Call Long Running Process
        }
    }
}

I am having problem creating JUnit test case for this use case. Do you have any idea how can I perform Unit Test for this class?

I wanted to actually mock up my response but I dont know how to do this. In my Unit Test, I dont want to actually call my ConfigService class.

2 answers

  • answered 2018-07-12 05:43 Niton

    if i understood right you want to test if the request is answered by a response. And that the response is the response you like to see rigth?
    I think your problem is that a Thread runs syncrone to your code and the test case will end bevore the response arrives.
    It is possible to hold the code in the JUnit Case as long as the listener Thread is alive.

    For this purpose you can use:

    Thread t = new WorkerThread();
    t.join();
    

    Thread.join(); prevents the code below from beeing executed as long as the Thread t is alive. So it blocks the code and will go on as the response is recived.

  • answered 2018-07-12 14:36 Code-Apprentice

    You should learn about mocking libraries like Mockito or EasyMock. This provide a way to inject a ConfigService instance that will return a known response which you can test against.

    Note that you should call workerThread.start() instead of workerThread.run() if you want the thread to run concurrently.