Powermockito:有效地使用thenReturn

时间:2012-07-12 18:37:11

标签: java mockito powermock

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

现在,是否有更高效/更清晰的方式来编写所有thenReturns,例如,在循环中?所以,我不必写出大量的thenReturns

由于

1 个答案:

答案 0 :(得分: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 clas:

public class Blub {
 public final int size() {
    return 0;
 }
}
相关问题