Test a controller with Junit?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















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










share|improve this question

























  • That doesn't make much sense: you're mocking two repositories that aren't used by your controller, but you're not mocking the one that is used. You're asking Mockito to create the controller and inject mocks for you, but then you create another instance by yourself. Regarding creating a Model, the javadoc gives the list of all classes implementing this interface.

    – JB Nizet
    Nov 23 '18 at 15:34











  • Also, Absence is spelt Absense, not Abscence, and Controller is spelt Controller (in English), or Controleur (in French), but not Controler.

    – JB Nizet
    Nov 23 '18 at 15:35











  • Using MockMvc you do not have to call methods of controllers, but rather simulate an HTTP request through the MockMvc API. Doing this, the Model parameter will be be built and injected by Spring.

    – Loïc Le Doyen
    Nov 24 '18 at 23:51




















1















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










share|improve this question

























  • That doesn't make much sense: you're mocking two repositories that aren't used by your controller, but you're not mocking the one that is used. You're asking Mockito to create the controller and inject mocks for you, but then you create another instance by yourself. Regarding creating a Model, the javadoc gives the list of all classes implementing this interface.

    – JB Nizet
    Nov 23 '18 at 15:34











  • Also, Absence is spelt Absense, not Abscence, and Controller is spelt Controller (in English), or Controleur (in French), but not Controler.

    – JB Nizet
    Nov 23 '18 at 15:35











  • Using MockMvc you do not have to call methods of controllers, but rather simulate an HTTP request through the MockMvc API. Doing this, the Model parameter will be be built and injected by Spring.

    – Loïc Le Doyen
    Nov 24 '18 at 23:51
















1












1








1








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










share|improve this question
















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







java unit-testing spring-boot junit mockito






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 16:16









Mureinik

187k22142207




187k22142207










asked Nov 23 '18 at 15:25









shasshas

8111




8111













  • That doesn't make much sense: you're mocking two repositories that aren't used by your controller, but you're not mocking the one that is used. You're asking Mockito to create the controller and inject mocks for you, but then you create another instance by yourself. Regarding creating a Model, the javadoc gives the list of all classes implementing this interface.

    – JB Nizet
    Nov 23 '18 at 15:34











  • Also, Absence is spelt Absense, not Abscence, and Controller is spelt Controller (in English), or Controleur (in French), but not Controler.

    – JB Nizet
    Nov 23 '18 at 15:35











  • Using MockMvc you do not have to call methods of controllers, but rather simulate an HTTP request through the MockMvc API. Doing this, the Model parameter will be be built and injected by Spring.

    – Loïc Le Doyen
    Nov 24 '18 at 23:51





















  • That doesn't make much sense: you're mocking two repositories that aren't used by your controller, but you're not mocking the one that is used. You're asking Mockito to create the controller and inject mocks for you, but then you create another instance by yourself. Regarding creating a Model, the javadoc gives the list of all classes implementing this interface.

    – JB Nizet
    Nov 23 '18 at 15:34











  • Also, Absence is spelt Absense, not Abscence, and Controller is spelt Controller (in English), or Controleur (in French), but not Controler.

    – JB Nizet
    Nov 23 '18 at 15:35











  • Using MockMvc you do not have to call methods of controllers, but rather simulate an HTTP request through the MockMvc API. Doing this, the Model parameter will be be built and injected by Spring.

    – Loïc Le Doyen
    Nov 24 '18 at 23:51



















That doesn't make much sense: you're mocking two repositories that aren't used by your controller, but you're not mocking the one that is used. You're asking Mockito to create the controller and inject mocks for you, but then you create another instance by yourself. Regarding creating a Model, the javadoc gives the list of all classes implementing this interface.

– JB Nizet
Nov 23 '18 at 15:34





That doesn't make much sense: you're mocking two repositories that aren't used by your controller, but you're not mocking the one that is used. You're asking Mockito to create the controller and inject mocks for you, but then you create another instance by yourself. Regarding creating a Model, the javadoc gives the list of all classes implementing this interface.

– JB Nizet
Nov 23 '18 at 15:34













Also, Absence is spelt Absense, not Abscence, and Controller is spelt Controller (in English), or Controleur (in French), but not Controler.

– JB Nizet
Nov 23 '18 at 15:35





Also, Absence is spelt Absense, not Abscence, and Controller is spelt Controller (in English), or Controleur (in French), but not Controler.

– JB Nizet
Nov 23 '18 at 15:35













Using MockMvc you do not have to call methods of controllers, but rather simulate an HTTP request through the MockMvc API. Doing this, the Model parameter will be be built and injected by Spring.

– Loïc Le Doyen
Nov 24 '18 at 23:51







Using MockMvc you do not have to call methods of controllers, but rather simulate an HTTP request through the MockMvc API. Doing this, the Model parameter will be be built and injected by Spring.

– Loïc Le Doyen
Nov 24 '18 at 23:51














1 Answer
1






active

oldest

votes


















2














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));
}





share|improve this answer
























  • thx, it work. i had some trouble cause intelij doesn't import the good any and eq by itself, but anyway, nice work!

    – shas
    Nov 26 '18 at 13:38












Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53449292%2ftest-a-controller-with-junit%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














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));
}





share|improve this answer
























  • thx, it work. i had some trouble cause intelij doesn't import the good any and eq by itself, but anyway, nice work!

    – shas
    Nov 26 '18 at 13:38
















2














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));
}





share|improve this answer
























  • thx, it work. i had some trouble cause intelij doesn't import the good any and eq by itself, but anyway, nice work!

    – shas
    Nov 26 '18 at 13:38














2












2








2







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));
}





share|improve this answer













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));
}






share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 23 '18 at 16:11









MureinikMureinik

187k22142207




187k22142207













  • thx, it work. i had some trouble cause intelij doesn't import the good any and eq by itself, but anyway, nice work!

    – shas
    Nov 26 '18 at 13:38



















  • thx, it work. i had some trouble cause intelij doesn't import the good any and eq by itself, but anyway, nice work!

    – shas
    Nov 26 '18 at 13:38

















thx, it work. i had some trouble cause intelij doesn't import the good any and eq by itself, but anyway, nice work!

– shas
Nov 26 '18 at 13:38





thx, it work. i had some trouble cause intelij doesn't import the good any and eq by itself, but anyway, nice work!

– shas
Nov 26 '18 at 13:38




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53449292%2ftest-a-controller-with-junit%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

Xamarin.form Move up view when keyboard appear

Post-Redirect-Get with Spring WebFlux and Thymeleaf

Anylogic : not able to use stopDelay()