1/* 2 * Copyright (c) 2007 Mockito contributors 3 * This program is made available under the terms of the MIT License. 4 */ 5 6package org.mockito.internal.stubbing.defaultanswers; 7 8import java.io.Serializable; 9import java.lang.reflect.Array; 10 11import org.mockito.Mockito; 12import org.mockito.invocation.InvocationOnMock; 13import org.mockito.stubbing.Answer; 14 15/** 16 * It's likely this implementation will be used by default by every Mockito 2.0 mock. 17 * <p> 18 * Currently <b>used only</b> by {@link Mockito#RETURNS_SMART_NULLS} 19 * <p> 20 * Current version of Mockito mocks by deafult use {@link ReturnsEmptyValues} 21 * <ul> 22 * <li> 23 * Returns appropriate primitive for primitive-returning methods 24 * </li> 25 * <li> 26 * Returns consistent values for primitive wrapper classes (e.g. int-returning method retuns 0 <b>and</b> Integer-returning method returns 0, too) 27 * </li> 28 * <li> 29 * Returns empty collection for collection-returning methods (works for most commonly used collection types) 30 * </li> 31 * <li> 32 * Returns empty array for array-returning methods 33 * </li> 34 * <li> 35 * Returns "" for String-returning method 36 * </li> 37 * <li> 38 * Returns description of mock for toString() method 39 * </li> 40 * <li> 41 * Returns non-zero for Comparable#compareTo(T other) method (see issue 184) 42 * </li> 43 * <li> 44 * Returns null for everything else 45 * </li> 46 * </ul> 47 */ 48public class ReturnsMoreEmptyValues implements Answer<Object>, Serializable { 49 50 private static final long serialVersionUID = -2816745041482698471L; 51 private Answer<Object> delegate = new ReturnsEmptyValues(); 52 53 /* (non-Javadoc) 54 * @see org.mockito.stubbing.Answer#answer(org.mockito.invocation.InvocationOnMock) 55 */ 56 public Object answer(InvocationOnMock invocation) throws Throwable { 57 Object ret = delegate.answer(invocation); 58 if (ret != null) { 59 return ret; 60 } 61 62 Class<?> returnType = invocation.getMethod().getReturnType(); 63 return returnValueFor(returnType); 64 } 65 66 Object returnValueFor(Class<?> type) { 67 if (type == String.class) { 68 return ""; 69 } else if (type.isArray()) { 70 Class<?> componenetType = type.getComponentType(); 71 return Array.newInstance(componenetType, 0); 72 } 73 return null; 74 } 75}