【问题标题】:how to mock inetaddress.getlocalhost().gethostname() to throw an exception如何模拟 inetaddress.getlocalhost().gethostname() 抛出异常
【发布时间】:2020-10-08 09:03:50
【问题描述】:

我希望我的 junit 测试覆盖包括来自接口的默认方法。以下是接口中的方法

public default String getServerAddress() {
    try {
        return InetAddress.getLocalHost().getHostAddress();
    } catch (Exception e) {
         return null;
    }
}

我的目标是涵盖此方法的异常部分。所以我可能需要模拟 InetAddress 以使其抛出异常。但我不确定如何? 我尝试模拟 inetAddress 并执行以下操作,但似乎不起作用:

when(inetAddress.getLocalHost().getHostAddress()).thenThrow(Exception.class)

【问题讨论】:

    标签: java testing junit mocking mockito


    【解决方案1】:

    你可以试试这样的:

    import org.junit.runner.RunWith;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    
    @RunWith( PowerMockRunner.class )
    @PrepareForTest( NetworkReader.class )
    public class Tests {
    
        @Test
        public void testGetServerAddress() {
            mockStatic(NetworkUtil.class);
            when(NetworkReader.getLocalHostname()).thenThrow(new Exception("exception message));
        
            // Here you could test your interface. 
        }
    }
    

    【讨论】:

    • 感谢您的回复,但很抱歉我没有使用 power-mockito 并且无法切换到它的一种方法.. 还有其他方法吗?
    • 不客气!我会说不幸的是没有,或者至少我现在知道这一点。具体来说,使用 power mockito 您可以模拟静态方法,而使用 mockito 则无法做到这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 2010-12-25
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    相关资源
    最近更新 更多