![](/img/trans.png)
[英]How can I get two method calls on the same Mock to return different values?
[英]I have two method calls in same line which I need to mock.How to mock it?
下面是我的代码。
String domain = service.getURL().getDomain();
为此,我试图用下面的代码来模拟。
when(serviceMock.getURL().getDomain()).thenReturn(someDomainName);
但是它抛出了空指针异常。
在这里,我正在执行两个不同的方法调用。 是否可以模拟上述情况?
您需要在这里使用多个模拟,以便“ 链式 ”调用能够正常工作,因为我不认为该模拟框架具有自动/递归模拟功能。
模拟service.getURL()
以返回模拟的URL对象,并模拟模拟URL对象的getDomain()
以根据需要进行操作。
//...
when(urlMock.getDomain()).thenReturn(someDomainName);
when(serviceMock.getURL()).thenReturn(urlMock);
//...
这样的话
String domain = service.getURL().getDomain();
被调用,它将表现出预期的效果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.