'mocking super class protected method returns null for @Mock on class variables

I am trying to write a unit test for a most common scenario.

class A{
  protected void m1() {
    //something
  }
}
//class A is from a different/external binary

class B extends A {
@Autowired Properties props
  public void m2() {
    //something
    if(props.getSomething()) {
      m1();
    }    
  }
}

class BTest {
  @Mock Properties props;

  @Test
  public void testM2() {
    MockB b = mock(MockB.class);
    doNothing().when(b).m1();
    when(b.m2()).thenCallRealMethod();
    when(props.getSomething()).thenReturn(1);
  }

  class MockB extends B {
   @Override
   public void m1() {
    return;
   }
  }
}

problem here is, as of now test is failing. When I tried debugging the test, I have observed null is being injected into props and this is causing NPE. When I remove class implementation from test, I can see props mock is working fine but it is failing at m1() call. Can someone please help me what I am missing here, I tried referring props with MockB b reference like b.props but this is also throwing NPE. Any help here is greatly appreciated.



Solution 1:[1]

I have used only mockito, You do not need the mock class, below should work

   class BTest {
        @Mock
        private Prop props;
    
        @Test
        public void testM2() {
            B bSpy = spy(new B(props));
            when(props.getSomething()).thenReturn(1);
            doNothing().when((A) bSpy).m1();
            doCallRealMethod().when(bSpy).m2();
            
            bSpy.m2();
        }
    }

If you use super.m1() this won't work

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1