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?
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.
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.
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.
You can call main method from junit test like this: YourClass. main(new String[] {"arg1", "arg2", "arg3"});
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With