Unit testing with inject annotation

Tags: , , ,



How do I unit test a class that uses @inject annotation:class A{

@inject
private B b;

void foo(){
    b.funcInClassB();
}

I am new to unit testing and having troubles testing this function because when calling b.funcInClassB() it throws NullPointerException because b is null. I wrote the following test:

class Atest{
   @MockBean
   private B b;
   @Test
   void foo(){
     when(b.funcInClassB()).willReturn("something");
      A a = new A();
      a.foo();
   }
}

Answer

I figured it out:

class Atest{
   @MockBean
   private B b;
   
   @Autowired
   A a;   

   @Test
   void foo(){
     when(b.funcInClassB()).willReturn("something");
      // A a = new A();
      a.foo();
   }
}


Source: stackoverflow