Skip to content

spy does not initialize objects fully with InstrumentationMemberAccessor #2947

@aswath80

Description

@aswath80

With mockito-inline, spy objects are missing fields when spying on child classes whose base class constructor is private. The issue goes away when base class constructor is made default access or public.

public class MockitoInnerClassSpyTest {

    static class P1 {

        @Override
        public String toString() {
            return "P1";
        }
    }

    static class P2 {

        @Override
        public String toString() {
            return "P2";
        }
    }

    static class C {

        private final P1 p1;

        private C(final P1 p1) {
            this.p1 = p1;
        }

        public void print() {
            System.out.println("C: p1=" + p1);
        }

        private static class D
            extends C {

            private final P2 p2;

            D(final P1 p1, final P2 p2) {
                super(p1);
                this.p2 = p2;
            }

            @Override
            public void print() {
                super.print();
                System.out.println("D: p2=" + p2);
            }
        }
    }

    @Test
    void test() {
        final C.D d = new C.D(new P1(), new P2());
        d.print();
        final C.D spy = spy(d);
        System.out.println("------------ spy ---------------");
        spy.print();
    }
}

This prints

C: p1=P1
D: p2=P2
------------ spy ---------------
C: p1=P1
D: p2=null

p2 is non-null in original object but becomes null in the spy. This issue does not happen in mockito-core with ReflectionMemberAccessor. If the constructor of C is made default or public, the issue does not occur.

Versions:

Mockito-Inline : 4.10
JDK - 17

check that

  • [x ] The mockito message in the stacktrace have useful information, but it didn't help
  • [ x] The problematic code (if that's possible) is copied here;
    Note that some configuration are impossible to mock via Mockito
  • [x ] Provide versions (mockito / jdk / os / any other relevant information)
  • [ x] Provide a Short, Self Contained, Correct (Compilable), Example of the issue
    (same as any question on stackoverflow.com)
  • [ x] Read the contributing guide

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions