Like a unit test class that implements Runnable

I have an ExampleThread class 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 a JUnit test for this class. I tried as below

 public class ExampleThreadTest { @Test(expected = IllegalArgumentException.class) public void shouldThrowIllegalArgumentExceptionForInvalidNumber() { ExampleThread exThread = new ExampleThread(-1); ExecutorService service = Executors.newSingleThreadExecutor(); service.execute(exThread); } } 

but it does not work. Is there any way to check this class to cover all the code?

+6
source share
2 answers

I think you want to check only if the run() method works correctly. At the moment you are also checking ServiceExecutor .

If you just want to write unit test, you have to call the run method in your test.

 public class ExampleThreadTest { @Test(expected = IllegalArgumentException.class) public void shouldThrowIllegalArgumentExceptionForInvalidNumber() { ExampleThread exThread = new ExampleThread(-1); exThread.run(); } } 
+10
source

From the Java Doc ,

void execute (Runnable command)

Executes the given command in the future. The command can be executed in a new thread, in a merged thread, or in the calling thread, at the discretion of the Executor implementation.

This means that the command did not complete execution until Testcase completed.

So, when an IllegalArgumentException not thrown before the completion of the test test. Consequently, he will fail.

You will need to wait until it finishes before completing the test case.

 @Test(expected = IllegalArgumentException.class) public void shouldThrowIllegalArgumentExceptionForInvalidNumber() { ExampleThread exThread = new ExampleThread(-1); ExecutorService service = Executors.newSingleThreadExecutor(); service.execute(exThread); // Add something like this. service.shutdown(); service.awaitTermination(<sometimeout>); } 
+2
source

All Articles