is it the moment to use @SpyBean?

92 Views Asked by At

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 ?

1

There are 1 best solutions below

0
Ruwanka De Silva On

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