001/* 002 * Copyright 2015 SirWellington Tech. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package tech.sirwellington.alchemy.test.mockito; 018 019import org.mockito.invocation.InvocationOnMock; 020import org.mockito.stubbing.Answer; 021import tech.sirwellington.alchemy.annotations.access.NonInstantiable; 022 023import static tech.sirwellington.alchemy.test.Checks.Internal.checkThat; 024 025/** 026 * This class contains a variety of useful answers for use in combination with Mockito. 027 * 028 * @author SirWellington 029 */ 030@NonInstantiable 031public final class MoreAnswers 032{ 033 034 MoreAnswers() throws IllegalAccessException 035 { 036 throw new IllegalAccessException("cannot instantiate class"); 037 } 038 039 040 /** 041 * For example: 042 * <p> 043 * <pre> 044 * 045 * {@code 046 * when(object.call("firstArg", 3)).then(returnFirst()); 047 * } 048 * Will return the {@code "firstArg"} string when it is called. 049 * </pre> 050 * 051 * @param <T> 052 * @return 053 * @see #returnArgumentAtIndex(int) 054 */ 055 public static <T> Answer<T> returnFirst() 056 { 057 return returnArgumentAtIndex(0); 058 } 059 060 /** 061 * An answer that returns one of the parameters as the return value. 062 * <p> 063 * Example: 064 * <pre> 065 * when(someMock.call(anyString(), anyString()).then(returnArgumentAtIndex(1)); 066 * 067 * String result = someMock.call("arg1", "arg2"); 068 * assertThat(result, is("arg2")); 069 * </pre> 070 * 071 * @param <T> 072 * @param index zero-based index which determines which parameter to return as an answer. 073 * @return 074 * @see #returnFirst() 075 */ 076 public static <T> Answer<T> returnArgumentAtIndex(final int index) 077 { 078 checkThat(index >= 0, "Index is out of bounds."); 079 080 return new Answer<T>() 081 { 082 @Override 083 public T answer(InvocationOnMock invocation) throws Throwable 084 { 085 if (index >= invocation.getArguments().length) 086 { 087 throw new IllegalArgumentException("Received an index of " + index + " but only " + invocation.getArguments().length + " arguments"); 088 } 089 090 return (T) invocation.getArguments()[index]; 091 } 092 }; 093 } 094}