diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/crud/controllers/UserController.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/crud/controllers/UserController.java index 8a7ef96f1e..fb86683d6b 100644 --- a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/crud/controllers/UserController.java +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/crud/controllers/UserController.java @@ -23,6 +23,12 @@ public class UserController { this.userRepository = userRepository; } + @GetMapping("/index") + public String showUserList(Model model) { + model.addAttribute("users", userRepository.findAll()); + return "index"; + } + @GetMapping("/signup") public String showSignUpForm(User user) { return "add-user"; @@ -35,7 +41,6 @@ public class UserController { } userRepository.save(user); - model.addAttribute("users", userRepository.findAll()); return "redirect:/index"; } @@ -43,6 +48,7 @@ public class UserController { public String showUpdateForm(@PathVariable("id") long id, Model model) { User user = userRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id)); model.addAttribute("user", user); + return "update-user"; } @@ -54,7 +60,7 @@ public class UserController { } userRepository.save(user); - model.addAttribute("users", userRepository.findAll()); + return "redirect:/index"; } @@ -62,7 +68,7 @@ public class UserController { public String deleteUser(@PathVariable("id") long id, Model model) { User user = userRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id)); userRepository.delete(user); - model.addAttribute("users", userRepository.findAll()); - return "index"; + + return "redirect:/index"; } } diff --git a/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/crud/UserControllerUnitTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/crud/UserControllerUnitTest.java index f1455f7a73..77d83698de 100644 --- a/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/crud/UserControllerUnitTest.java +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/crud/UserControllerUnitTest.java @@ -28,6 +28,11 @@ public class UserControllerUnitTest { userController = new UserController(mockedUserRepository); } + @Test + public void whenCalledIndex_thenCorrect() { + assertThat(userController.showUserList(mockedModel)).isEqualTo("index"); + } + @Test public void whenCalledshowSignUpForm_thenCorrect() { User user = new User("John", "john@domain.com"); @@ -78,6 +83,6 @@ public class UserControllerUnitTest { @Test(expected = IllegalArgumentException.class) public void whenCalleddeleteUser_thenIllegalArgumentException() { - assertThat(userController.deleteUser(1l, mockedModel)).isEqualTo("index"); + assertThat(userController.deleteUser(1l, mockedModel)).isEqualTo("redirect:/index"); } }