connectException和IOException的单元测试

时间:2016-10-07 21:26:45

标签: java junit

我有单元测试,测试方法是否抛出错误。

@Test
public void getStockPriceWithNetworkErrorThrowsException()
{
    StockPriceFetcher stockPriceFetcherWithNetworkError = Mockito.mock(StockPriceFetcher.class);
    when(stockPriceFetcherWithNetworkError.getPrice("YHOO"))
            .thenThrow(new ConnectException("Network error"));

    assetValue = new AssetValue(stockPriceFetcherWithNetworkError);

    try
    {
        assetValue.getStockPrice("YHOO");
        fail("Expected exception for network error.");
    }
    catch(ConnectException e){
        assertEquals(e.getMessage(), "Network error");
    }
}

getPrice是来自界面stockPriceFetcher的方法,getStockPrice只返回getPrice()返回的内容。我想要抛出ConnectException,但我在catch块中有一个错误,因为ConnectException永远不会在try块中抛出。

无论如何,我可以让这个尝试块抛出一个ConnectException

3 个答案:

答案 0 :(得分:0)

解决这个问题的最简单方法是替换以下行:

  

当(stockPriceFetcherWithNetworkError。的用getPrice ( “YHOO”))

行:

  

当(stockPriceFetcherWithNetworkError。的 getStockPrice ( “YHOO”))

但请确保getStockPrice()包含try {} catch(ConnectException e){}块。

似乎你没有在getStockPrice()方法中抛出ConnectException。

getStockPrice(String str) {

    getPrice(str) {
     //  Here the ConnectException is thrown
     }
   // here should appear another catch that throws the error to the upper level
}

如果没有getStockPrice()方法中的try {} catch {}块,则无法在调用该方法的任何位置捕获异常。 这就是你应该为getStockPrice()实现模拟的原因。

当您添加try {} catch(ConnectException e){}块时,它将运行良好。

答案 1 :(得分:0)

使用expected参数扩充@Test注释。

@Test(expected=ConnectException.class)
public void testConnectExceptionThrown() {
    // your test here
}

只有在测试方法的执行中抛出预期的异常时,测试才会通过。如果测试在没有未被捕获的ConnectException的情况下结束,则会将其视为失败。这通常是您测试异常的方式。

当然,如果你想测试异常的消息,那就不会削减它。你需要以你已经写好的方式来完成它。但是,我会将断言移出catch块。

@Test
public void getStockPriceWithNetworkErrorThrowsException()
{
    StockPriceFetcher stockPriceFetcherWithNetworkError = Mockito.mock(StockPriceFetcher.class);
    when(stockPriceFetcherWithNetworkError.getPrice("YHOO"))
            .thenThrow(new ConnectException("Network error"));

    assetValue = new AssetValue(stockPriceFetcherWithNetworkError);

    String exceptionMsg = null;
    try
    {
        assetValue.getStockPrice("YHOO");
        fail("Expected exception for network error.");
    }
    catch(ConnectException e){
        exceptionMsg = e.getMessage();
    }

    assertEquals("Should have thrown ConnectException with correct message",
        "Network error", exceptionMsg);
}

答案 2 :(得分:0)

根据评论中讨论的内容,我几乎可以肯定你的问题是getStockPrice没有进一步抛出它从getPrice获得的异常,所以基本上它没有达到它的目的被抛出到调用getStockPrice的实例(例如你的测试类)。

你可以做的是:

  • 修改您的测试,以准确预期来自catch getStockPrice块中发生的情况如果,那就是您希望系统具有 OR <的行为/强>

  • 修改您的getStockPrice方法以抛出从getPrice获取的异常,而不是捕获它,即向其添加throws声明并删除try...catch块。然后,您的测试将按照预期的方式运行