Skip to content
Advertisement

Unit testing with inject annotation

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();
   }
}

Advertisement

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();
   }
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement