Test a controller with Junit?
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
add a comment |
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
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
UsingMockMvc
you do not have to call methods of controllers, but rather simulate an HTTP request through theMockMvc
API. Doing this, theModel
parameter will be be built and injected by Spring.
– Loïc Le Doyen
Nov 24 '18 at 23:51
add a comment |
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
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
java unit-testing spring-boot junit mockito
edited Nov 23 '18 at 16:16
Mureinik
182k22134200
182k22134200
asked Nov 23 '18 at 15:25
![](https://i.stack.imgur.com/u3Cxx.jpg?s=32&g=1)
![](https://i.stack.imgur.com/u3Cxx.jpg?s=32&g=1)
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
UsingMockMvc
you do not have to call methods of controllers, but rather simulate an HTTP request through theMockMvc
API. Doing this, theModel
parameter will be be built and injected by Spring.
– Loïc Le Doyen
Nov 24 '18 at 23:51
add a comment |
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
UsingMockMvc
you do not have to call methods of controllers, but rather simulate an HTTP request through theMockMvc
API. Doing this, theModel
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
add a comment |
1 Answer
1
active
oldest
votes
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));
}
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
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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));
}
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
add a comment |
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));
}
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
add a comment |
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));
}
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 Nov 23 '18 at 16:11
MureinikMureinik
182k22134200
182k22134200
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
add a comment |
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
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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 theMockMvc
API. Doing this, theModel
parameter will be be built and injected by Spring.– Loïc Le Doyen
Nov 24 '18 at 23:51