How to test a controller function with argument form?












2














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









share|improve this question









New contributor




Sky Blue is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • There would be some class extending in your application extending EmployeeRegistrationForm
    – Aditya Narayan Dixit
    2 days ago
















2














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









share|improve this question









New contributor




Sky Blue is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • There would be some class extending in your application extending EmployeeRegistrationForm
    – Aditya Narayan Dixit
    2 days ago














2












2








2


1





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









share|improve this question









New contributor




Sky Blue is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











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






share|improve this question









New contributor




Sky Blue is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Sky Blue is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 2 days ago









Lionel Montrieux

5215




5215






New contributor




Sky Blue is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 2 days ago









Sky Blue

112




112




New contributor




Sky Blue is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Sky Blue is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Sky Blue is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • 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
















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












1 Answer
1






active

oldest

votes


















0















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.






share|improve this answer





















    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.










    draft saved

    draft discarded


















    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









    0















    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.






    share|improve this answer


























      0















      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.






      share|improve this answer
























        0












        0








        0







        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.






        share|improve this answer













        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.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 13 hours ago









        Oleksandr Shpota

        3,42621431




        3,42621431






















            Sky Blue is a new contributor. Be nice, and check out our Code of Conduct.










            draft saved

            draft discarded


















            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.




            draft saved


            draft discarded














            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





















































            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







            Popular posts from this blog

            Monofisismo

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas