MockCreationValidator.java revision e0ae5d7e87b1dd6e789803c1b9615a84bd7488b7
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.util;
6
7import org.mockito.exceptions.Reporter;
8import org.mockito.internal.util.reflection.Constructors;
9
10import java.io.Serializable;
11import java.util.Collection;
12
13@SuppressWarnings("unchecked")
14public class MockCreationValidator {
15
16    private final MockUtil mockUtil = new MockUtil();
17
18    public void validateType(Class classToMock) {
19        if (!mockUtil.isTypeMockable(classToMock)) {
20            new Reporter().cannotMockFinalClass(classToMock);
21        }
22    }
23
24    public void validateExtraInterfaces(Class classToMock, Collection<Class> extraInterfaces) {
25        if (extraInterfaces == null) {
26            return;
27        }
28
29        for (Class i : extraInterfaces) {
30            if (classToMock == i) {
31                new Reporter().extraInterfacesCannotContainMockedType(classToMock);
32            }
33        }
34    }
35
36    public void validateMockedType(Class classToMock, Object spiedInstance) {
37        if (classToMock == null || spiedInstance == null) {
38            return;
39        }
40        if (!classToMock.equals(spiedInstance.getClass())) {
41            new Reporter().mockedTypeIsInconsistentWithSpiedInstanceType(classToMock, spiedInstance);
42        }
43    }
44
45    public void validateDelegatedInstance(Class classToMock, Object delegatedInstance) {
46        if (classToMock == null || delegatedInstance == null) {
47            return;
48        }
49        if (delegatedInstance.getClass().isAssignableFrom(classToMock)) {
50            new Reporter().mockedTypeIsInconsistentWithDelegatedInstanceType(classToMock, delegatedInstance);
51        }
52    }
53
54    public void validateSerializable(Class classToMock, boolean serializable) {
55        // We can't catch all the errors with this piece of code
56        // Having a **superclass that do not implements Serializable** might fail as well when serialized
57        // Though it might prevent issues when mockito is mocking a class without superclass.
58        if(serializable
59                && !classToMock.isInterface()
60                && !(Serializable.class.isAssignableFrom(classToMock))
61                && Constructors.noArgConstructorOf(classToMock) == null
62                ) {
63            new Reporter().serializableWontWorkForObjectsThatDontImplementSerializable(classToMock);
64        }
65    }
66}