JUnit测试Try/Catch异常



我似乎无法访问JUnit测试方法中的Exception。方法如下:

public void doUpdateStocks() {
    for (Entry<Integer, IFolioRestricted> e : folioList.entrySet()) {
        IFolioRestricted folio = e.getValue();
        for(Entry<Integer, IStockRestricted> s : folio.getStockList().entrySet()){
            try {
                ((IStock) (s.getValue())).updatePrice();
            } catch (MethodException e1) {
                e1.printStackTrace();
            }
        }
    }

这就是我测试它的方式:

    @Test
    public void testUpdateStock() {
        h.doCreateNewFolio("a");
        try {
            h.doBuyStock(0, "A", 10);
        } catch (IOException | WebsiteDataException | NoSuchTickerException | MethodException e) {
            // TODO Auto-generated catch block
        }
        h.doUpdateStocks();
    }

在网上查看后,我看到了(预期=MethodException.class),但它似乎不起作用。有人知道如何在JUnit中覆盖catch(MethodException e1){e1.printStackTrace();}吗?

首先,您需要抛出异常以便在JUnit测试中捕获它:

public void doUpdateStocks() throws MethodException { // throw the exception
    for (Entry<Integer, IFolioRestricted> e : folioList.entrySet()) {
    IFolioRestricted folio = e.getValue();
    for(Entry<Integer, IStockRestricted> s : folio.getStockList().entrySet()){
       ((IStock) (s.getValue())).updatePrice();           
    }
}

您的代码应该已经工作了,但如果没有抛出异常,您将不得不失败测试:

try {
    h.doBuyStock(0, "A", 10);
    // No exception thrown, thats wrong so fail the test
    Assert.fail()
} catch (IOException | WebsiteDataException | NoSuchTickerException | MethodException e) {
    // This is where you want to end
}

除了抛出异常(您肯定必须这样做)之外,还有一种更好的方法可以使用https://github.com/Codearte/catch-exception

看看github上的示例。

最新更新