1

I have to unit test my service layer but I don't know how to do it as I am new to SpringMvc.

Here is the method I want to test:

@Override
public String update(String username, User newUserData, BindingResult result, Model model) {
    if (result.hasErrors()) {
        updateModelData(model, "", result.getAllErrors());
        return HOME_VIEW_NAME;
    }

    User foundUser = this.userRepository.findByUsername(username);
    if (foundUser == null) {
        throw new UserNotFoundException(username);
    }

    String queryResult = String.format("UPDATED SUCCESSFULLY: \n Old User: %s", foundUser);
    foundUser.setPassword(encryptPassword(newUserData.getPassword()));
    foundUser.setStatus(newUserData.getStatus());
    queryResult += String.format("New User: %s", foundUser);

    this.userRepository.save(foundUser);

    updateModelData(model, queryResult, new ArrayList<>());
    return HOME_VIEW_NAME;
}

First - I would like to know if it is a good idea to keep the Model, BindingResult and return a page in the Service layer? If no, why not?

Second - How should I test this method correctly?

Thank you!

2
  • 3
    First no because these should stay in your controller and your service should contain only the code to update/save your user. Second in unit test with mock. Commented Jun 21, 2019 at 12:44
  • Thank you! I will refactor this code to decouple logic from UI processing
    – John P
    Commented Jun 21, 2019 at 12:51

1 Answer 1

3

I think that it's best to return pages in the controller. I believe the Spring developers created such annotations @Component, @Repository, @Service, @Controller is to also provide context for whichever layer that specific component belongs to. You can check this discussion on SO regarding that.

On your second question, you may want to check out the Spring MVC test framework. You may want to check out MockMvc, there are tons of references in the documentation as well as on the Spring projects repository.

I think you'd need something like the snippet below if you'd like to test your scenario where it went to the correct view after updating:

MockMvc mockMvc;

mockMvc.perform(get("/path/to/update/resource"))
            .andExpect(status().isOk())
            .andExpect(modelAndView().getViewName().isEqualTo("your_view_name"));

Not the answer you're looking for? Browse other questions tagged or ask your own question.