Hello,

I am trying to do a Delegate test on class with SpyBean dependency,

    Delegate {
        @Inject
     A a;

          execute() {
         a.execute();
    }
     }
   class TestSetUp {
        @SpyBean A a;
    @SpyBean B b;

    @Before
        public void setUp() {
          MockitoAnnotations.openMocks(this);
    }
  }
   class Test extended TestSetUp {
      @Resource
          @InjectMocks
      Delegate delegate;

      @Test
      public void testDelegate() {
        delegate.execute();
      }
   }

In real implementation the class A inject class B and another classes.

    class A {
        @Inject 
        B b;
        @Inject 
        C c;
        ...
    }

In the test scenario I expected that the spy class A will contain a spybean object B, but all members of class a are null. The spy object b in the Test is not null. Why are all the members of the spy object a in the Test class is null?

versions used
spring-boot-test-2.6.4.jar
mockito-core-4.0.0.jar
mockito-junit-jupiter-4.0.0.jar

Comment From: wilkinsona

I suspect that there's no existing A or B beans. When the instances are created for the spies no dependency injection is performed so their fields are left as null. That said, it's rather hard to tell what's happing from a few snippets of source code. If you would like us to spend some more time investigating, please spend some time providing a complete yet minimal sample that reproduces the problem. You can share it with us by pushing it to a separate repository on GitHub or by zipping it up and attaching it to this issue.

Comment From: VasilyBorisovich

The bean existing I'm do inject for SpyBean B in the Test class, it's ok ( first picture) The SpyBean A also exist but all members (and SpyBean B) are null (secondary picture) SpyBeanExisted SpyMockExist_memeber_isNull

Comment From: wilkinsona

Unfortunately, a screenshot doesn't really help. As I said above, if you would like us to spend some more time investigating, please spend some time providing a complete yet minimal sample that reproduces the problem.

Comment From: mdeinum

Your test uses mockito to create the mocks/spies (the @Before annotated method). The @SpyBean is a Spring Boot annotation which should be processed by Spring Boot and not Mockito. You need one of the Spring Boot test annotations for the @SpyBean or @MockBean to work and not plain Mockito.

Comment From: spring-projects-issues

If you would like us to look at this issue, please provide the requested information. If the information is not provided within the next 7 days this issue will be closed.

Comment From: spring-projects-issues

Closing due to lack of requested feedback. If you would like us to look at this issue, please provide the requested information and we will re-open the issue.