下面列出了怎么用org.mockito.internal.stubbing.answers.ReturnsArgumentAt的API类实例代码及写法,或者点击链接到github查看源代码。
@Before
public void setUp() {
configuration = Mockito.mock(Configuration.class);
Answer answer = new ReturnsArgumentAt(1);
when(configuration.getProperty(Mockito.anyString(), Mockito.anyString())).thenAnswer(answer);
when(configuration.getBooleanProperty(Mockito.anyString(), Mockito.anyBoolean())).thenAnswer(answer);
when(configuration.getIntProperty(Mockito.anyString(), anyInt())).thenAnswer(answer);
addresses = new Address[] { new Address("localhost", AMQP.PROTOCOL.PORT) };
}
@Test
public void should_raise_an_exception_if_index_is_not_in_allowed_range_at_creation_time() throws Throwable {
try {
new ReturnsArgumentAt(-30);
fail();
} catch (Exception e) {
assertThat(e.getMessage())
.containsIgnoringCase("argument index")
.containsIgnoringCase("positive number")
.contains("1")
.containsIgnoringCase("last argument");
}
}
@Test
public void should_be_able_to_return_the_first_parameter() throws Throwable {
assertThat(new ReturnsArgumentAt(0).answer(invocationWith("A", "B"))).isEqualTo("A");
}
@Test
public void should_be_able_to_return_the_second_parameter()
throws Throwable {
assertThat(new ReturnsArgumentAt(1).answer(invocationWith("A", "B", "C"))).isEqualTo("B");
}
@Test
public void should_be_able_to_return_the_last_parameter() throws Throwable {
assertThat(new ReturnsArgumentAt(-1).answer(invocationWith("A"))).isEqualTo("A");
assertThat(new ReturnsArgumentAt(-1).answer(invocationWith("A", "B"))).isEqualTo("B");
}
@Test
public void should_be_able_to_return_the_specified_parameter() throws Throwable {
assertThat(new ReturnsArgumentAt(0).answer(invocationWith("A", "B", "C"))).isEqualTo("A");
assertThat(new ReturnsArgumentAt(1).answer(invocationWith("A", "B", "C"))).isEqualTo("B");
assertThat(new ReturnsArgumentAt(2).answer(invocationWith("A", "B", "C"))).isEqualTo("C");
}
@Before
public void setup() {
when(interpreter.renderFlat(anyString())).thenAnswer(new ReturnsArgumentAt(0));
}
/**
* Returns the parameter of an invocation at the given position.
*
* <p>
* This additional answer could be used at stub time using the
* <code>then|do|will{@link org.mockito.stubbing.Answer}</code> methods. For example :
* </p>
*
* <pre class="code"><code class="java">given(person.remember(dream1, dream2, dream3, dream4)).will(returnsArgAt(3));
* doAnswer(returnsArgAt(3)).when(person).remember(dream1, dream2, dream3, dream4)</code></pre>
*
* @param <T> Return type of the invocation.
* @return Answer that will return the second argument of the invocation.
*
* @since 1.9.5
*/
public static <T> Answer<T> returnsArgAt(int position) {
return (Answer<T>) new ReturnsArgumentAt(position);
}