Issue
I had some trouble setting up unit test with my spring boot application. My main issue is with the "model" object that's needed in my controller, but I can't find a way to recreate it in my test, which is required to use my function.
here are the function I want to test
@Controller
public class AjoutAbscenceControler {
@Autowired
private AbsenceRepository absenceRepository;
@RequestMapping(value = { "/addAbsence" }, method = RequestMethod.GET)
public String showAddAbsencePage(Model model) {
Absence absence = new Absence();
model.addAttribute("Absence", absence);
return "addAbsence";
}
@RequestMapping(value = { "/addingAbsence" }, method = RequestMethod.POST)
public String saveAbsence(Model model, @ModelAttribute("absence") Absence absence) {
if (absence.getName() != null && absence.getName().length() > 0) {
absenceRepository.save(absence);
}
return "redirect:/userList";
}
}
I did try something like that
@RunWith(MockitoJUnitRunner.class)
public class AjoutAbscenceControlerTest {
@Mock
VacationRepository vacationRepository;
@Mock
CategoryRepository categoryRepository;
@InjectMocks
AjoutAbscenceControler controler;
public MockMvc mockMvc;
@Before
public void setUp() throws Exception{
mockMvc = MockMvcBuilders.standaloneSetup(controler).build();
}
@Test
public void showAddAbsencePagetest() {
AjoutAbscenceControler ajoutAbscenceControler =new AjoutAbscenceControler();
assertEquals("addAbsence",ajoutAbscenceControler.showAddAbsencePage(controler));
}
}
but I don't find any way to create a springfarmwork.ui.Model
Solution
If you're testing the logic of your controller you probably shouldn't create a Model
object, but mock it, and verify the interactions against it:
@Mock
private Model model;
@Test
public void showAddAbsencePagetest() {
// Should probably be initialized in a @Before method,
// Initialized here for clarity only
AjoutAbscenceControler ajoutAbscenceControler = new AjoutAbscenceControler();
assertEquals("addAbsence", ajoutAbscenceControler.showAddAbsencePage(model));
Mockito.verify(model).addAttribute(eq("Absence"), any(Absence.class));
}
Answered By - Mureinik