you can check the original answer
https://stackoverflow.com/a/71591567/5108695
But this is very common problem so I posted the answer here also
In my opinion, we are writing unit test cases and we should not initialize the spring context in order to test a piece of code.
So,
I used Mockito to mock the Autowired
beans in my main target test class and injected those mock beans in my main test class Object
maybe sounds confusing, see the following example
Dependencies I used
testImplementation("org.mockito:mockito-core:2.28.2")
testImplementation("org.mockito:mockito-inline:2.13.0")
testImplementation("org.junit.jupiter:junit-jupiter:5.8.2")
testImplementation("org.mockito:mockito-junit-jupiter:4.0.0")
My main class is Maths and Calculator bean is autowired
class Maths{
@Autowired Calculator cal;
.........
.........
public void randomAddMethod(){
cal.addTwoNumbers(1,2); // will return 3;
}
}
Test class
@ExtendWith(MockitoExtension.class)
class MathsTest{
@Mock(answer = Answers.RETURNS_DEEP_STUBS) Calculator cal;
@InjectMocks Maths maths = new Maths();
@Test testMethodToCheckCalObjectIsNotNull(){
maths.randomAddMethod();
}
}
Now cal
will not be null in Maths class and will work as expected