1 /* 2 * Copyright (c) 2007 Mockito contributors 3 * This program is made available under the terms of the MIT License. 4 */ 5 package org.mockito.internal.util; 6 7 import static org.mockito.internal.exceptions.Reporter.cannotMockClass; 8 import static org.mockito.internal.exceptions.Reporter.extraInterfacesCannotContainMockedType; 9 import static org.mockito.internal.exceptions.Reporter.mockedTypeIsInconsistentWithDelegatedInstanceType; 10 import static org.mockito.internal.exceptions.Reporter.mockedTypeIsInconsistentWithSpiedInstanceType; 11 import static org.mockito.internal.exceptions.Reporter.usingConstructorWithFancySerializable; 12 13 import java.util.Collection; 14 15 import org.mockito.mock.SerializableMode; 16 import org.mockito.plugins.MockMaker.TypeMockability; 17 18 @SuppressWarnings("unchecked") 19 public class MockCreationValidator { 20 validateType(Class<?> classToMock)21 public void validateType(Class<?> classToMock) { 22 TypeMockability typeMockability = MockUtil.typeMockabilityOf(classToMock); 23 if (!typeMockability.mockable()) { 24 throw cannotMockClass(classToMock, typeMockability.nonMockableReason()); 25 } 26 } 27 validateExtraInterfaces(Class<?> classToMock, Collection<Class<?>> extraInterfaces)28 public void validateExtraInterfaces(Class<?> classToMock, Collection<Class<?>> extraInterfaces) { 29 if (extraInterfaces == null) { 30 return; 31 } 32 33 for (Class<?> i : extraInterfaces) { 34 if (classToMock == i) { 35 throw extraInterfacesCannotContainMockedType(classToMock); 36 } 37 } 38 } 39 validateMockedType(Class<?> classToMock, Object spiedInstance)40 public void validateMockedType(Class<?> classToMock, Object spiedInstance) { 41 if (classToMock == null || spiedInstance == null) { 42 return; 43 } 44 if (!classToMock.equals(spiedInstance.getClass())) { 45 throw mockedTypeIsInconsistentWithSpiedInstanceType(classToMock, spiedInstance); 46 } 47 } 48 validateDelegatedInstance(Class<?> classToMock, Object delegatedInstance)49 public void validateDelegatedInstance(Class<?> classToMock, Object delegatedInstance) { 50 if (classToMock == null || delegatedInstance == null) { 51 return; 52 } 53 if (delegatedInstance.getClass().isAssignableFrom(classToMock)) { 54 throw mockedTypeIsInconsistentWithDelegatedInstanceType(classToMock, delegatedInstance); 55 } 56 } 57 validateConstructorUse(boolean usingConstructor, SerializableMode mode)58 public void validateConstructorUse(boolean usingConstructor, SerializableMode mode) { 59 if (usingConstructor && mode == SerializableMode.ACROSS_CLASSLOADERS) { 60 throw usingConstructorWithFancySerializable(mode); 61 } 62 } 63 } 64