Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何创建涉及抛出异常的JUnit测试?_Java_Junit - Fatal编程技术网

Java 如何创建涉及抛出异常的JUnit测试?

Java 如何创建涉及抛出异常的JUnit测试?,java,junit,Java,Junit,如何在run函数中测试异常 ` public void run() { ArrayBlockingQueue<String> bookQueue = library.getBookQueue(book); try { bookQueue.take(); try { updateState(State.IN_PROGRESS); Thread.sleep(READ_T

如何在
run
函数中测试异常

 `    public void run() {
     ArrayBlockingQueue<String> bookQueue = 
     library.getBookQueue(book);
     try {
        bookQueue.take();
        try {
            updateState(State.IN_PROGRESS);
            Thread.sleep(READ_TIME_MS);
            bookQueue.put(book);
            updateState(State.ENDED);
        } catch(InterruptedException e){
            bookQueue.put(book);
        }
    } catch(InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    finally {
        updateState(State.ENDED);
    }
   }`
`public void run(){
ArrayBlockingQueue bookQueue=
library.getBookQueue(book);
试一试{
bookQueue.take();
试一试{
更新不动产(状态为进行中);
线程睡眠(读取时间毫秒);
bookQueue.put(书);
不动产(州结束);
}捕捉(中断异常e){
bookQueue.put(书);
}
}捕捉(中断异常e){
Thread.currentThread().interrupt();
}
最后{
不动产(州结束);
}
}`

@Test
注释中,您可以指定预期的异常

例如

@Test(expected=IndexOutOfBoundsException.class) 
 public void outOfBounds() {
   new ArrayList<Object>().get(1);
}
我们还可以通过考虑注释中的@GhostCat
建议来改善这一点,您可以在测试方法中添加
try-catch`

@Test
 public void testRun() {
    tyr {
       run();
      Asserts.fail(); // 
      }
     catch(Exception ex) {
      assertTrue(//some condition);
      assertEquals(//some condition);
     }
 }

如果
run()
方法没有抛出任何异常,测试将因为
断言而失败。fail()
,或者在任何异常情况下
catch
block assert语句将被执行

您所要求的是什么,这是非常不清楚的。什么样的例外?关于模拟框架,你以前做过什么样的研究?你自己做了什么测试?可能重复:更新谢谢你的建议和指导,我需要学习很多@Ghostcatt要做到完美,你可以在捕获块上声明一些东西。这就是这里的要点:您可以从生产代码中检查更多关于异常的信息,而不是它的类。
@Test
 public void testRun() {
    tyr {
       run();
      Asserts.fail(); // 
      }
     catch(Exception ex) {
      assertTrue(//some condition);
      assertEquals(//some condition);
     }
 }