gpt4 book ai didi

java - Powermockito : using thenReturn efficiently

转载 作者:行者123 更新时间:2023-11-30 07:24:35 25 4
gpt4 key购买 nike

我模拟了一个名为 methodA() 的方法。
我有一个名为 linkedListA 的链表。现在,
我有一行代码来模拟 methodA 的返回,这样
when(methodA()).thenReturn(linkedListA.get(0)).thenReturn(linkedListA.get(1)).thenReturn(linkedListA.get(2)) 等等

现在,是否有一种更有效/更清晰的方式来编写所有的 thenReturns,例如,就像在一个循环中一样?所以,我不必写大量的 thenReturns

谢谢

最佳答案

我认为第一个改进是使用这个:

when(methodA()).thenReturn(linkedListA.get(0), linkedListA.get(1), linkedListA.get(2)) and so on

此外,您可以使用 thenAnswer 方法返回一个值:

final AtomicInteger i = new AtomicInteger(0);
when(methodA()).thenAnswer(new Answer<YourType>() {

@Override
public YourType answer(InvocationOnMock invocation) {
return linkedListA.get(i.getAndIncrement());
}
});

例子:

import static org.powermock.api.mockito.PowerMockito.when;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(Blub.class)
public class Mockexample {

@Test
public void test() {
Blub blub = PowerMockito.mock(Blub.class);
final List<Integer> counter = Arrays.asList(1, 2, 3);
final AtomicInteger i = new AtomicInteger(0);

// blub.size() is final, only reason to use PowerMockito here
when(blub.size()).thenAnswer(new Answer<Integer>() {

@Override
public Integer answer(InvocationOnMock invocation) throws Throwable {
return counter.get(i.getAndIncrement());
}

});
System.out.println(blub.size());
System.out.println(blub.size());
System.out.println(blub.size());
}

}

Blub 类:

public class Blub {
public final int size() {
return 0;
}
}

关于java - Powermockito : using thenReturn efficiently,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11458409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com