How to test a controller function with argument form?
Heads Up: It is my first post here, please excuse any missing information or the really novice questions.
So I am currently trying to write jUnit tests for the already finished web application that uses spring (everything works, I just have to get full coverage with the tests).
I have the classes: "Employee", "EmployeeController" and "EmployeeManagement".
I want to test the "registerNew" function which creates a new Employee with the filled form "EmployeeRegistrationForm" if it has no errors ("Errors result").
Now I want to write a Test for this to make sure that the function really does create a new object "Employee" which should be saved in the "EmployeeRepository" with said form.
However, I cannot seem to be able to create a filled "EmployeeForm" since it is abstract and cannot be instantiated. Therefore I am struggling to give any argument to that function and do not know how to pass the information needed for the test to function being tested.
@Service
@Transactional
public class EmployeeManagement {
private final EmployeeRepository employees;
private final UserAccountManager userAccounts;
EmployeeManagement(EmployeeRepository employees, UserAccountManager userAccounts) {
Assert.notNull(employees, "employeeRepository must not be null!");
Assert.notNull(userAccounts, "UserAccountManager must not be null!");
this.employees=employees;
this.userAccounts = userAccounts;
}
//the function that creates the employee
public Employee createEmployee(EmployeeRegistrationForm form) {
Assert.notNull(form, "Registration form must not be null!");
String type = form.getType();
Role role = this.setRole(type);
UserAccount useraccount = userAccounts.create(form.getUsername(), form.getPassword(), role);
useraccount.setFirstname(form.getFirstname());
useraccount.setLastname(form.getLastname());
return employees.save(new Employee(form.getNumber(), form.getAddress(), useraccount));
}
@Controller
public class EmployeeController {
private final EmployeeManagement employeeManagement;
EmployeeController(EmployeeManagement employeeManagement) {
Assert.notNull(employeeManagement, "userManagement must not be null!");
this.employeeManagement = employeeManagement;
}
@PostMapping("/registerEmployee")
@PreAuthorize("hasRole('ROLE_ADMIN')")
String registerNew(@Valid EmployeeRegistrationForm form, Errors result) {
if (result.hasErrors()) {
return "registerEmployee";
}
employeeManagement.createEmployee(form);
return "redirect:/";
}
public interface EmployeeRegistrationForm {
@NotEmpty(message = "{RegistrationForm.firstname.NotEmpty}")
String getFirstname();
@NotEmpty(message = "{RegistrationForm.lastname.NotEmpty}")
String getLastname();
@NotEmpty(message = "{RegistrationForm.password.NotEmpty}")
String getPassword();
@NotEmpty(message = "{RegistrationForm.address.NotEmpty}")
String getAddress();
@NotEmpty(message = "{RegistrationForm.number.NotEmpty}")
String getNumber();
@NotEmpty(message = "{RegistrationForm.type.NotEmpty}")
String getType();
@NotEmpty(message = "{RegistrationForm.username.NotEmpty}")
String getUsername();
}
java forms spring-mvc junit controller
New contributor
add a comment |
Heads Up: It is my first post here, please excuse any missing information or the really novice questions.
So I am currently trying to write jUnit tests for the already finished web application that uses spring (everything works, I just have to get full coverage with the tests).
I have the classes: "Employee", "EmployeeController" and "EmployeeManagement".
I want to test the "registerNew" function which creates a new Employee with the filled form "EmployeeRegistrationForm" if it has no errors ("Errors result").
Now I want to write a Test for this to make sure that the function really does create a new object "Employee" which should be saved in the "EmployeeRepository" with said form.
However, I cannot seem to be able to create a filled "EmployeeForm" since it is abstract and cannot be instantiated. Therefore I am struggling to give any argument to that function and do not know how to pass the information needed for the test to function being tested.
@Service
@Transactional
public class EmployeeManagement {
private final EmployeeRepository employees;
private final UserAccountManager userAccounts;
EmployeeManagement(EmployeeRepository employees, UserAccountManager userAccounts) {
Assert.notNull(employees, "employeeRepository must not be null!");
Assert.notNull(userAccounts, "UserAccountManager must not be null!");
this.employees=employees;
this.userAccounts = userAccounts;
}
//the function that creates the employee
public Employee createEmployee(EmployeeRegistrationForm form) {
Assert.notNull(form, "Registration form must not be null!");
String type = form.getType();
Role role = this.setRole(type);
UserAccount useraccount = userAccounts.create(form.getUsername(), form.getPassword(), role);
useraccount.setFirstname(form.getFirstname());
useraccount.setLastname(form.getLastname());
return employees.save(new Employee(form.getNumber(), form.getAddress(), useraccount));
}
@Controller
public class EmployeeController {
private final EmployeeManagement employeeManagement;
EmployeeController(EmployeeManagement employeeManagement) {
Assert.notNull(employeeManagement, "userManagement must not be null!");
this.employeeManagement = employeeManagement;
}
@PostMapping("/registerEmployee")
@PreAuthorize("hasRole('ROLE_ADMIN')")
String registerNew(@Valid EmployeeRegistrationForm form, Errors result) {
if (result.hasErrors()) {
return "registerEmployee";
}
employeeManagement.createEmployee(form);
return "redirect:/";
}
public interface EmployeeRegistrationForm {
@NotEmpty(message = "{RegistrationForm.firstname.NotEmpty}")
String getFirstname();
@NotEmpty(message = "{RegistrationForm.lastname.NotEmpty}")
String getLastname();
@NotEmpty(message = "{RegistrationForm.password.NotEmpty}")
String getPassword();
@NotEmpty(message = "{RegistrationForm.address.NotEmpty}")
String getAddress();
@NotEmpty(message = "{RegistrationForm.number.NotEmpty}")
String getNumber();
@NotEmpty(message = "{RegistrationForm.type.NotEmpty}")
String getType();
@NotEmpty(message = "{RegistrationForm.username.NotEmpty}")
String getUsername();
}
java forms spring-mvc junit controller
New contributor
There would be some class extending in your application extendingEmployeeRegistrationForm
– Aditya Narayan Dixit
2 days ago
add a comment |
Heads Up: It is my first post here, please excuse any missing information or the really novice questions.
So I am currently trying to write jUnit tests for the already finished web application that uses spring (everything works, I just have to get full coverage with the tests).
I have the classes: "Employee", "EmployeeController" and "EmployeeManagement".
I want to test the "registerNew" function which creates a new Employee with the filled form "EmployeeRegistrationForm" if it has no errors ("Errors result").
Now I want to write a Test for this to make sure that the function really does create a new object "Employee" which should be saved in the "EmployeeRepository" with said form.
However, I cannot seem to be able to create a filled "EmployeeForm" since it is abstract and cannot be instantiated. Therefore I am struggling to give any argument to that function and do not know how to pass the information needed for the test to function being tested.
@Service
@Transactional
public class EmployeeManagement {
private final EmployeeRepository employees;
private final UserAccountManager userAccounts;
EmployeeManagement(EmployeeRepository employees, UserAccountManager userAccounts) {
Assert.notNull(employees, "employeeRepository must not be null!");
Assert.notNull(userAccounts, "UserAccountManager must not be null!");
this.employees=employees;
this.userAccounts = userAccounts;
}
//the function that creates the employee
public Employee createEmployee(EmployeeRegistrationForm form) {
Assert.notNull(form, "Registration form must not be null!");
String type = form.getType();
Role role = this.setRole(type);
UserAccount useraccount = userAccounts.create(form.getUsername(), form.getPassword(), role);
useraccount.setFirstname(form.getFirstname());
useraccount.setLastname(form.getLastname());
return employees.save(new Employee(form.getNumber(), form.getAddress(), useraccount));
}
@Controller
public class EmployeeController {
private final EmployeeManagement employeeManagement;
EmployeeController(EmployeeManagement employeeManagement) {
Assert.notNull(employeeManagement, "userManagement must not be null!");
this.employeeManagement = employeeManagement;
}
@PostMapping("/registerEmployee")
@PreAuthorize("hasRole('ROLE_ADMIN')")
String registerNew(@Valid EmployeeRegistrationForm form, Errors result) {
if (result.hasErrors()) {
return "registerEmployee";
}
employeeManagement.createEmployee(form);
return "redirect:/";
}
public interface EmployeeRegistrationForm {
@NotEmpty(message = "{RegistrationForm.firstname.NotEmpty}")
String getFirstname();
@NotEmpty(message = "{RegistrationForm.lastname.NotEmpty}")
String getLastname();
@NotEmpty(message = "{RegistrationForm.password.NotEmpty}")
String getPassword();
@NotEmpty(message = "{RegistrationForm.address.NotEmpty}")
String getAddress();
@NotEmpty(message = "{RegistrationForm.number.NotEmpty}")
String getNumber();
@NotEmpty(message = "{RegistrationForm.type.NotEmpty}")
String getType();
@NotEmpty(message = "{RegistrationForm.username.NotEmpty}")
String getUsername();
}
java forms spring-mvc junit controller
New contributor
Heads Up: It is my first post here, please excuse any missing information or the really novice questions.
So I am currently trying to write jUnit tests for the already finished web application that uses spring (everything works, I just have to get full coverage with the tests).
I have the classes: "Employee", "EmployeeController" and "EmployeeManagement".
I want to test the "registerNew" function which creates a new Employee with the filled form "EmployeeRegistrationForm" if it has no errors ("Errors result").
Now I want to write a Test for this to make sure that the function really does create a new object "Employee" which should be saved in the "EmployeeRepository" with said form.
However, I cannot seem to be able to create a filled "EmployeeForm" since it is abstract and cannot be instantiated. Therefore I am struggling to give any argument to that function and do not know how to pass the information needed for the test to function being tested.
@Service
@Transactional
public class EmployeeManagement {
private final EmployeeRepository employees;
private final UserAccountManager userAccounts;
EmployeeManagement(EmployeeRepository employees, UserAccountManager userAccounts) {
Assert.notNull(employees, "employeeRepository must not be null!");
Assert.notNull(userAccounts, "UserAccountManager must not be null!");
this.employees=employees;
this.userAccounts = userAccounts;
}
//the function that creates the employee
public Employee createEmployee(EmployeeRegistrationForm form) {
Assert.notNull(form, "Registration form must not be null!");
String type = form.getType();
Role role = this.setRole(type);
UserAccount useraccount = userAccounts.create(form.getUsername(), form.getPassword(), role);
useraccount.setFirstname(form.getFirstname());
useraccount.setLastname(form.getLastname());
return employees.save(new Employee(form.getNumber(), form.getAddress(), useraccount));
}
@Controller
public class EmployeeController {
private final EmployeeManagement employeeManagement;
EmployeeController(EmployeeManagement employeeManagement) {
Assert.notNull(employeeManagement, "userManagement must not be null!");
this.employeeManagement = employeeManagement;
}
@PostMapping("/registerEmployee")
@PreAuthorize("hasRole('ROLE_ADMIN')")
String registerNew(@Valid EmployeeRegistrationForm form, Errors result) {
if (result.hasErrors()) {
return "registerEmployee";
}
employeeManagement.createEmployee(form);
return "redirect:/";
}
public interface EmployeeRegistrationForm {
@NotEmpty(message = "{RegistrationForm.firstname.NotEmpty}")
String getFirstname();
@NotEmpty(message = "{RegistrationForm.lastname.NotEmpty}")
String getLastname();
@NotEmpty(message = "{RegistrationForm.password.NotEmpty}")
String getPassword();
@NotEmpty(message = "{RegistrationForm.address.NotEmpty}")
String getAddress();
@NotEmpty(message = "{RegistrationForm.number.NotEmpty}")
String getNumber();
@NotEmpty(message = "{RegistrationForm.type.NotEmpty}")
String getType();
@NotEmpty(message = "{RegistrationForm.username.NotEmpty}")
String getUsername();
}
java forms spring-mvc junit controller
java forms spring-mvc junit controller
New contributor
New contributor
edited 2 days ago
Lionel Montrieux
5215
5215
New contributor
asked 2 days ago
Sky Blue
112
112
New contributor
New contributor
There would be some class extending in your application extendingEmployeeRegistrationForm
– Aditya Narayan Dixit
2 days ago
add a comment |
There would be some class extending in your application extendingEmployeeRegistrationForm
– Aditya Narayan Dixit
2 days ago
There would be some class extending in your application extending
EmployeeRegistrationForm
– Aditya Narayan Dixit
2 days ago
There would be some class extending in your application extending
EmployeeRegistrationForm
– Aditya Narayan Dixit
2 days ago
add a comment |
1 Answer
1
active
oldest
votes
However, I cannot seem to be able to create a filled "EmployeeForm" since it is abstract and cannot be instantiated.
Use Mockito to instantiate your abstract classes.
You can use it like this:
EmployeeForm form = mock(EmployeeForm.class);
Now you have an instance of EmployeeForm
which you can pass to your methods. If you need to call some methods from your mock you can do somethifg like this:
given(form.getFirstname()).willReturn("John");
This way the form will behave the way you want.
Note: mock()
comes from org.mockito.Mockito
and given
comes from org.mockito.BDDMockito
.
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
});
}
});
Sky Blue is a new contributor. Be nice, and check out our Code of Conduct.
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%2f53945532%2fhow-to-test-a-controller-function-with-argument-form%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
However, I cannot seem to be able to create a filled "EmployeeForm" since it is abstract and cannot be instantiated.
Use Mockito to instantiate your abstract classes.
You can use it like this:
EmployeeForm form = mock(EmployeeForm.class);
Now you have an instance of EmployeeForm
which you can pass to your methods. If you need to call some methods from your mock you can do somethifg like this:
given(form.getFirstname()).willReturn("John");
This way the form will behave the way you want.
Note: mock()
comes from org.mockito.Mockito
and given
comes from org.mockito.BDDMockito
.
add a comment |
However, I cannot seem to be able to create a filled "EmployeeForm" since it is abstract and cannot be instantiated.
Use Mockito to instantiate your abstract classes.
You can use it like this:
EmployeeForm form = mock(EmployeeForm.class);
Now you have an instance of EmployeeForm
which you can pass to your methods. If you need to call some methods from your mock you can do somethifg like this:
given(form.getFirstname()).willReturn("John");
This way the form will behave the way you want.
Note: mock()
comes from org.mockito.Mockito
and given
comes from org.mockito.BDDMockito
.
add a comment |
However, I cannot seem to be able to create a filled "EmployeeForm" since it is abstract and cannot be instantiated.
Use Mockito to instantiate your abstract classes.
You can use it like this:
EmployeeForm form = mock(EmployeeForm.class);
Now you have an instance of EmployeeForm
which you can pass to your methods. If you need to call some methods from your mock you can do somethifg like this:
given(form.getFirstname()).willReturn("John");
This way the form will behave the way you want.
Note: mock()
comes from org.mockito.Mockito
and given
comes from org.mockito.BDDMockito
.
However, I cannot seem to be able to create a filled "EmployeeForm" since it is abstract and cannot be instantiated.
Use Mockito to instantiate your abstract classes.
You can use it like this:
EmployeeForm form = mock(EmployeeForm.class);
Now you have an instance of EmployeeForm
which you can pass to your methods. If you need to call some methods from your mock you can do somethifg like this:
given(form.getFirstname()).willReturn("John");
This way the form will behave the way you want.
Note: mock()
comes from org.mockito.Mockito
and given
comes from org.mockito.BDDMockito
.
answered 13 hours ago
Oleksandr Shpota
3,42621431
3,42621431
add a comment |
add a comment |
Sky Blue is a new contributor. Be nice, and check out our Code of Conduct.
Sky Blue is a new contributor. Be nice, and check out our Code of Conduct.
Sky Blue is a new contributor. Be nice, and check out our Code of Conduct.
Sky Blue is a new contributor. Be nice, and check out our Code of Conduct.
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.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- 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%2f53945532%2fhow-to-test-a-controller-function-with-argument-form%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
There would be some class extending in your application extending
EmployeeRegistrationForm
– Aditya Narayan Dixit
2 days ago