我可以使用doReturn将PowerMockito的退货链接起来吗?

编程入门 行业动态 更新时间:2024-10-26 06:28:25
本文介绍了我可以使用doReturn将PowerMockito的退货链接起来吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个方法调用,它需要在第一次调用valueA时返回,而在第二次调用valueB时返回。我使用的是PowerMockito间谍,因此,如果我只需要返回一个值,它将看起来像这样:

I have a method call that needs to return valueA the first time it is called and valueB the second time it is called. I'm using a PowerMockito spy, so if I were just needing to return one value it would look like this:

PowerMockito.doReturn(valueA).when(mockedObject, "methodName");

看起来我可以像这样进行连锁回报:

It looks like I can do chained returns like this:

PowerMockito.when(mockedObject, "methodName").thenReturn(valueA).thenReturn(valueB);

但是我需要用doReturn指示链接的返回值,这样才不会调用真正的methodName()我的间谍。

But I need to indicate chained returns with doReturn so that the real methodName() isn't called on my Spy.

我已经尝试过了,但是Eclipse给了我一个错误,说它甚至无法编译:

I've tried this, but Eclipse gives me an error saying that it won't even compile:

PowerMockito.doReturn(valueA).doReturn(valueB).when(mockedObject, "methodName");

是否甚至可以通过doReturn和powermockito链接回报?如果可以,怎么办?

Is it even possible to chain returns with doReturn and powermockito? If so, how?

推荐答案

我不这样认为。相反,您可以使用如下所示的doAnswer和Queue

I don't think so. Rather, You can achieve it with using doAnswer and Queue like below

@Test public void testReturnChain() throws Exception { Example example = new Example() { public String getValue() { return null; } }; Example mockExample = spy(example); PowerMockito.doAnswer(new Answer<String>() { private final Queue<String> values = new LinkedList<String>(Arrays.asList("firstValue", "secondValue")); public String answer(InvocationOnMock invocationOnMock) throws Throwable { return values.poll(); } }).when(mockExample, "getValue"); System.out.println(mockExample.getValue()); System.out.println(mockExample.getValue()); System.out.println(mockExample.getValue()); }

更多推荐

我可以使用doReturn将PowerMockito的退货链接起来吗?

本文发布于:2023-10-31 07:14:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545399.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可以使用   链接   doReturn   PowerMockito

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!