I have application written in spring boot
.
I am using testNG
and mockito
for unit testing.
I am bit confuse with working of unit tests.
Following is my test class
class StudentServiceTest {
@mock
StudentDAO studentDAO;
@InjectMocks
StudentService studentService;
@BeforeMethod
public void initMock() {
studentService = new StudentService();
MockitoAnnotations.initMocks(this);
}
@Test(dataprovider.....)
public void shouldxxxxx(int id......) {
when(studentDAO.findOne(id)).thenReturn(Student);
assert......
}
}
When I run above test. It works fine.
I have following doubts.
- Does it involves spring. If not then how @mock and other code works
- Should we involve spring.If not/yes why?
- I have used new key word to initialize service. Is it good. As in spring unit test documentation they have said that
You can simply instantiate objects using the new operator without even involving Spring. You can also use mock objects instead of real dependencies
If I not instantiate service with new keyword then it show error "Cannot instantiate @InjectMocks".
If I autowired
service then it requires spring container and it I run even single test, it takes too much time to run. And If not autowired
and use new
keyword then it runs very fast.
- Does above code is clean? Please do suggest best practice to write unit test in spring boot with testNg and mockito.