我有一个实现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);
}
}
}
我如何为此类编写JUnit测试。我已经尝试过如下
public class ExampleThreadTest {
@Test(expected = IllegalArgumentException.class)
public void shouldThrowIllegalArgumentExceptionForInvalidNumber() {
ExampleThread exThread = new ExampleThread(-1);
ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(exThread);
}
}
但这是行不通的。有什么办法可以测试此类以覆盖所有代码?
最佳答案
我猜您只想测试run()
方法是否做对了。目前,您还测试了ServiceExecutor
。
如果只想编写单元测试,则应在测试中调用run
方法。
public class ExampleThreadTest {
@Test(expected = IllegalArgumentException.class)
public void shouldThrowIllegalArgumentExceptionForInvalidNumber() {
ExampleThread exThread = new ExampleThread(-1);
exThread.run();
}
}