Java – how to unit test a class that implements runnable
•
Java
I have a class that implements the runnable interface, examplethread
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 to write JUnit tests for this class I've tried the following
public class ExampleThreadTest { @Test(expected = IllegalArgumentException.class) public void shouldThrowIllegalArgumentExceptionForInvalidNumber() { ExampleThread exThread = new ExampleThread(-1); ExecutorService service = Executors.newSingleThreadExecutor(); service.execute(exThread); } }
But it doesn't work Is there any way to test this class to cover all the code?
Solution
I think you just want to test the run () method for correctness At this point, you will also test serviceexecutor
If you just want to write unit tests, you should call the run method in the test.
public class ExampleThreadTest { @Test(expected = IllegalArgumentException.class) public void shouldThrowIllegalArgumentExceptionForInvalidNumber() { ExampleThread exThread = new ExampleThread(-1); exThread.run(); } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码