Home > OS >  Problems with Unit_Tests
Problems with Unit_Tests

Time:06-06

I am trying to write UNIT Test for my controller in MVC - Spring Boot , actually i am new to it . I have added dependency of Unit testing in pom/xml. Here is my controller :

@GetMapping("/showFormForUpdate/{id}")
    public String showFormForUpdate(@PathVariable ( value = "id") long id, Model model) {
        
        // get employee from the service
        Employee employee = employeeService.getEmployeeById(id);
        
        // set employee as a model attribute to pre-populate the form
        model.addAttribute("employee", employee);
        return "update_employee";
    }

Here is what i did:

public class ControllerTests {

@Test
void hello(){
    EmployeeController controller = new EmployeeController();//Arrange
    String response = controller.showFormForUpdate( long id);

}

}

How could i write a good Unit test for this?

CodePudding user response:

Spring offers @WebMvcTest for controller layer slicing test. (Strictly, it is not unit test. but also not integrated test.)

https://spring.io/guides/gs/testing-web/

for example

@WebMvcTest
public class YourTest() {
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void hello() {
       this.mockMvc
           .perform(get("/showFormForUpdate/111"))
           .andDo(print())
           .andExpect(status().isOk())     
    }
}
  • Related