如何对实现 Runnable 的 class 进行单元测试

How to unit test a class that implements Runnable

我有一个 class ExampleThread 实现了 Runnable 接口。

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

如何为此 class 编写 JUnit 测试。我试过如下

public class ExampleThreadTest {

    @Test(expected = IllegalArgumentException.class)
    public void shouldThrowIllegalArgumentExceptionForInvalidNumber() {
        ExampleThread exThread = new ExampleThread(-1);

        ExecutorService service = Executors.newSingleThreadExecutor();
        service.execute(exThread);
    }
}

但这不起作用。有什么方法可以测试这个 class 以覆盖所有代码吗?

来自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.

这意味着,在 Testcase 完成之前,命令不会完成执行。

所以,当 IllegalArgumentException 在测试用例完成之前没有抛出。因此它会失败。

您需要等待它完成才能完成测试用例。

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

我想您只想测试 run() 方法是否正确。目前您还测试了 ServiceExecutor.

如果您只想编写单元测试,您应该在测试中调用 run 方法。

public class ExampleThreadTest {

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