简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM