我有一个方法调用,它需要在第一次调用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的退货链接起来吗?
发布评论