mockito 如何模拟inetaddress.getlocalhost().gethostname()来抛出异常

mutmk8jj  于 9个月前  发布在  其他
关注(0)|答案(2)|浏览(97)

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

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

我的目标是覆盖这个方法的异常部分。所以我可能需要模拟InetAddress来使它抛出异常。但我不知道怎么做?我尝试模仿inetAddress并执行以下操作,但似乎不起作用:

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

sy5wg1nm1#

你可以试试这样的东西:

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. 
    }
}
i7uaboj4

i7uaboj42#

即使使用Mockito(从3.4.0开始),也可以模拟静态方法。参见文档或tutorial
另一种可能性是将静态调用 Package 到您自己的类中,并将其注入到最终使用位置。你的 Package 器对象可以用标准的方式被模仿。

相关问题