Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test a class that implements Runnable

I have a class ExampleThread that implements the Runnable interface.

public class ExampleThread implements Runnable {

    private int myVar;

    public ExampleThread(int var) {
        this.myVar = var;
    }

    @Override
    public void run() {
        if (this.myVar < 0) {
            throw new IllegalArgumentException("Number less than Zero");
        } else {
            System.out.println("Number is " + this.myVar);
        }
    }
}

How can I write JUnit test for this class. I have tried like below

public class ExampleThreadTest {

    @Test(expected = IllegalArgumentException.class)
    public void shouldThrowIllegalArgumentExceptionForInvalidNumber() {
        ExampleThread exThread = new ExampleThread(-1);

        ExecutorService service = Executors.newSingleThreadExecutor();
        service.execute(exThread);
    }
}

but this does not work. Is there any way I can test this class to cover all code?

like image 457
ѕтƒ Avatar asked Aug 11 '15 05:08

ѕтƒ


People also ask

How do you implement a runnable class?

Steps to create a new thread using RunnableCreate a Runnable implementer and implement the run() method. Instantiate the Thread class and pass the implementer to the Thread, Thread has a constructor which accepts Runnable instances. Invoke start() of Thread instance, start internally calls run() of the implementer.

How does run () method in runnable work?

When the object of a class implementing Runnable class is used to create a thread, then the run method is invoked in the thread which executes separately. The runnable interface provides a standard set of rules for the instances of classes which wish to execute code when they are active.

Can a runnable return result?

With Runnable. The Runnable interface is a functional interface and has a single run() method that doesn't accept any parameters or return any values. In this example, the thread will just read a message from the queue and log it in a log file. There's no value returned from the task.

Can we run the Junit test from the main method of the class?

You can call main method from junit test like this: YourClass. main(new String[] {"arg1", "arg2", "arg3"});


1 Answers

I guess you only want to test if the run() method does the right thing. At the moment you also test the ServiceExecutor.

If you just want to write a unit test you should call the run method in your test.

public class ExampleThreadTest {

    @Test(expected = IllegalArgumentException.class)
    public void shouldThrowIllegalArgumentExceptionForInvalidNumber() {
        ExampleThread exThread = new ExampleThread(-1);
        exThread.run();
    }
}
like image 193
René Link Avatar answered Sep 17 '22 21:09

René Link