All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.mockito.internal.invocation.mockref.MockWeakReference Maven / Gradle / Ivy

There is a newer version: 5.12.0
Show newest version
/*
 * Copyright (c) 2018 Mockito contributors
 * This program is made available under the terms of the MIT License.
 */
package org.mockito.internal.invocation.mockref;

import java.io.ObjectStreamException;
import java.lang.ref.WeakReference;

/**
 * A weak reference that is converted into a strong reference when serialized.
 * See {@link MockReference}.
 */
public class MockWeakReference implements MockReference {

    private final WeakReference ref;

    public MockWeakReference(T t) {
        this.ref = new WeakReference(t);
    }

    private Object writeReplace() throws ObjectStreamException {
        return new MockStrongReference(get(), true);
    }

    @Override
    public T get() {
        T ref = this.ref.get();

        if (ref == null) {
            throw new IllegalStateException(
                    "The mock object was garbage collected. "
                            + "This should not happen in normal circumstances when using public API. "
                            + "Typically, the test class keeps strong reference to the mock object "
                            + "and it prevents getting the mock collected. Mockito internally needs "
                            + "to keep weak references to mock objects to avoid memory leaks for "
                            + "certain types of MockMaker implementations. If you see this exception "
                            + "using Mockito public API, please file a bug. For more information see "
                            + "issue #1313.");
        }

        return ref;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy