If you want to do unit testing then you would not have to connect to the DB. Connecting to DB's and other external services would be considered integration testing. So the request to the DB would be mocked out when testing your StudentService
class.
Second point worth mentioning is that you would test your controller class and you service class separately, but in your case those tests would look very similar.
Below is one way you can test your controller's insertStrundent
method.
@RunWith(MockitoJUnitRunner.class)
public class TestStudentContoller {
@Mock
StundentService mockStudentService;
@InjectMocks
StudentController studentController = new StudentController();
@Test
public void testInsertStudent(){
Student student = new Student();
studentContoller.insertStudent(student);
verify(studentService, times(1)).insertStudent(student);
}
Since you controller's insertStudent
method has no if statements and only one branch, there is basically only one test that needs to be performed, basically does the controller call the service.
Another way it can be tested is with Springs MockMvc
. The good thing about the MockMvc
is that it lets you test the HTTP request. For example in this case you would want to test that your controller's insertStudent
method will properly respond to HTTP POST requests with a JSON Student.
@RunWith(MockitoJUnitRunner.class)
public class TestStudentContoller {
@Mock
StundentService mockStudentService;
@InjectMocks
StudentController studentController = new StudentController();
MockMvc mockMvc;
@Before
public void setup(){
mockMvc = MockMvcBuilders.standAloneSetup(studentController).build();
}
@Test
public void testInsertStudent(){
mockMvc.perform(post("path/to/insert/student")
.accept(MediaType.APPLICATION_JSON)
.andExpect(status().isOk())
.andExpect(content().string("{}"));//put json student in here
verify(studentService, times(1)).insertStudent(student);
}
MockMvc
has other cool methods you should explore.