简体   繁体   English

Mockito 不返回预期的字符串,而是返回模拟对象

[英]Mockito not returning expected String instead it returning mocked object

I am mocking InetAddress , When I am mocking this I am getting mocked object instead of my expected string我在嘲笑InetAddress ,当我嘲笑这个时,我得到的是模拟对象而不是我预期的字符串

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

I think It should print test in a console but it is printing mocked object hashcode.我认为它应该在控制台中打印test但它正在打印模拟对象哈希码。

Mockito.when(inetAddress.getHostName()).thenReturn("test")

With this line, you are saying mockito that when I call the inetAddress.getHostName() return me "test".使用这一行,您是在说当我调用 inetAddress.getHostName() 返回我“测试”时的模拟。 You have done this declaration however, you have not call this mocked method to see what happens,instead you are printing mockito object which refers to an address like all other objects do in java.但是,您已经完成了这个声明,您没有调用这个模拟方法来查看会发生什么,而是打印了模拟对象,该对象引用了一个地址,就像 java 中的所有其他对象一样。 To see results, after creation of mocking object you should:要查看结果,在创建模拟对象后,您应该:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM