How to unit test a class that implements Runnable

17,579

Solution 1

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();
    }
}

Solution 2

From the Java Doc,

void execute(Runnable command)

Executes the given command at some time in the future. The command may execute in a new thread, in a pooled thread, or in the calling thread, at the discretion of the Executor implementation.

Which means, the command wouldn't have finished executing before the the Testcase finished.

So, when IllegalArgumentException is not thrown before the testcase finished. Hence it would fail.

You will need to wait for it to finish 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>);
}
Share:
17,579

Related videos on Youtube

ѕтƒ
Author by

ѕтƒ

˙·٠•●♥ Ƹ̵̡Ӝ̵̨̄Ʒ ♥●•٠·˙ вє α ѕтαя ˙·٠•●♥ Ƹ̵̡Ӝ̵̨̄Ʒ ♥●•٠·˙

Updated on September 16, 2022

Comments

  • ѕтƒ
    ѕтƒ over 1 year

    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?

    • Florian Schaetz
      Florian Schaetz over 8 years
      Testing Threads is not that easy, but for this case, I would simply test the run method by calling it directly (without ExecutorService). If you really need to test System.out, you can set it to something else and check the content then.