【问题标题】:Mockito not returning expected String instead it returning mocked objectMockito 没有返回预期的字符串,而是返回了模拟对象
【发布时间】:2019-01-24 08:46:11
【问题描述】:

我在模拟 InetAddress,当我在模拟这个时,我得到的是模拟对象而不是我预期的字符串

    InetAddress inetAddress = Mockito.mock(InetAddress.class);
    Mockito.when(inetAddress.getHostName()).thenReturn("test")
    System.out.printinetAddress.getHostName());

我认为它应该在控制台中打印 test 但它正在打印模拟对象哈希码。

【问题讨论】:

标签: java junit mockito inetaddress


【解决方案1】:
Mockito.when(inetAddress.getHostName()).thenReturn("test")

通过这一行,您在说当我调用 inetAddress.getHostName() 时返回“测试”。但是,您已经完成了此声明,您还没有调用此模拟方法来查看发生了什么,而是打印了 mockito 对象,该对象与 java 中的所有其他对象一样引用地址。要查看结果,在创建模拟对象后,您应该:

System.out.println(inetAddress.getHostName());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    • 2011-07-29
    • 2012-11-26
    相关资源
    最近更新 更多