How do I unit test a class that uses @inject
annotation:class A{
JavaScript
x
@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:
JavaScript
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:
JavaScript
class Atest{
@MockBean
private B b;
@Autowired
A a;
@Test
void foo(){
when(b.funcInClassB()).willReturn("something");
// A a = new A();
a.foo();
}
}