0

i have a bean like this one

@Service
public class SpringParent {

    @Resource
    SpringChild sc;

    public String giveChild() {
        return sc.giveChild();
    }

}

and a test class like this one..

public class InjectMock3 {

    @Spy
    SpringParent sp;

    @Test
    public void test() {
        sp.giveChild();
        verify(sp).giveChild();
    }

}

then a message like

Cannot invoke "com.coussy.SpringChild.giveChild()" because sc is null

So, my question/thinking is : is it the moment to replace @Spy by @SpyBean or is there another method ?

Sören
  • 1,803
  • 2
  • 16
  • 23
  • 1
    What are you trying to test? `sp.giveChild(); verify(sp).giveChild();` is rather useless – it is obvious that the previous statement has called `giveChild`, why verify the call; don't you trust the compiler and JVM? – knittl Jul 30 '23 at 20:49

1 Answers1

0

Yes

If your bean/component/service etc. is initialized and managed by spring context then you have to use @SpyBean

More on this available in @SpyBean documentation. Also have a look at this question which explains differences between @Spy and @SpyBean

Basically @Spy for everything that is not in Spring Context, and @SpyBean for everything that managed by Spring Context. This applies for all other counterparts as well for an example @Mock vs @MockBean

Ruwanka De Silva
  • 3,555
  • 6
  • 35
  • 51