2

我嘲笑了一个名为methodA().
我有一个名为linkedListA. 现在,
我有一行代码来模拟methodA, as such 等
when(methodA()).thenReturn(linkedListA.get(0)).thenReturn(linkedListA.get(1)).thenReturn(linkedListA.get(2))的 返回

现在,是否有一种更有效/更清洁的方式来编写所有的thenReturns,例如,像循环一样?所以,我不必写很多thenReturns

谢谢

4

1 回答 1

4

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

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;
 }
}
于 2012-07-12T18:48:03.263 回答