1/* 2 * Copyright (c) 2007 Mockito contributors 3 * This program is made available under the terms of the MIT License. 4 */ 5package org.mockito.internal.handler; 6 7import static org.mockito.internal.util.Primitives.defaultValue; 8 9import java.util.List; 10 11import org.mockito.internal.InternalMockHandler; 12import org.mockito.internal.stubbing.InvocationContainer; 13import org.mockito.invocation.Invocation; 14import org.mockito.mock.MockCreationSettings; 15import org.mockito.stubbing.Answer; 16 17/** 18 * Protects the results from delegate MockHandler. Makes sure the results are valid. 19 * 20 * by Szczepan Faber, created at: 5/22/12 21 */ 22class NullResultGuardian<T> implements InternalMockHandler<T> { 23 24 private final InternalMockHandler<T> delegate; 25 26 public NullResultGuardian(InternalMockHandler<T> delegate) { 27 this.delegate = delegate; 28 } 29 30 @Override 31 public Object handle(Invocation invocation) throws Throwable { 32 Object result = delegate.handle(invocation); 33 Class<?> returnType = invocation.getMethod().getReturnType(); 34 if(result == null && returnType.isPrimitive()) { 35 //primitive values cannot be null 36 return defaultValue(returnType); 37 } 38 return result; 39 } 40 41 @Override 42 public MockCreationSettings<T> getMockSettings() { 43 return delegate.getMockSettings(); 44 } 45 46 @Override 47 public void setAnswersForStubbing(List<Answer<?>> answers) { 48 delegate.setAnswersForStubbing(answers); 49 } 50 51 @Override 52 public InvocationContainer getInvocationContainer() { 53 return delegate.getInvocationContainer(); 54 } 55} 56