解決したいこと
Springboot、javaでコードを書き、VSコードで新規登録画面のテストを行なっています。
新規登録成功時に[/signin]へ移動、失敗時に[/signup]へ移動を作成しているのですが、
うまくテストの期待値が返ってこず、エラーになります。
アドバイスよろしくお願いします!
例)
発生している問題・エラー
Testで成功時に/signinと記述していますが、エラーはsignupが返ってくると出ます。
SignupControllerTest.testSignup_Success:85 Redirected URL expected:</signin> but was:</signup>
SignupControllerTest.testSignup_Failure:102 Status expected:<200> but was:<302>
該当するソースコード
SignupControllerはこちらです。
@PostMapping("/signup")
public String signup(@Valid @ModelAttribute SignupForm form, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
return "signup";
}
String message = userService.addUser(form);
if ("ユーザーアカウントが新しく登録されました".equals(message)) {
redirectAttributes.addFlashAttribute("successMessage", "サインアップ成功しました");
return "redirect:/signin";
} else {
redirectAttributes.addFlashAttribute("errorMessage", "記入に誤りがあります");
return "redirect:/signup";
}
}
SignupControllerTestはこちらです。
@Test
public void testShowSignupForm() throws Exception {
mockMvc.perform(get("/signup"))
.andExpect(status().isOk())
.andExpect(view().name("signup"))
.andExpect(model().attributeExists("signupForm"));
}
@Test
public void testSignup_Success() throws Exception {
mockMvc.perform(post("/signup")
.param("lastName", "Test")
.param("firstName", "User")
.param("email", "test@example.com")
.param("password", "password123")
.param("storeId", "1")
.param("authorityId", "2")
.param("positionId", "3"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/signin"))
.andExpect(flash().attribute("successMessage", "サインアップ成功しました"));
}
@Test
public void testSignup_Failure() throws Exception {
when(userService.addUser(any(SignupForm.class))).thenReturn("エラーメッセージ");
MvcResult result = mockMvc.perform(post("/signup")
.param("lastName", "Test")
.param("firstName", "User")
.param("email", "testuser@example.com")
.param("password", "password123")
.param("authorityId", "1")
.param("positionId", "1")
.param("storeId", "1"))
.andExpect(status().isOk())
.andExpect(view().name("signup"))
.andExpect(model().attributeExists("signupForm"))
.andExpect(model().attribute("signupForm", hasProperty("errorMessage", is("記入に誤りがあります"))))
.andReturn();
// FlashAttributesの検証
FlashMap flashMap = result.getFlashMap();
assertNotNull(flashMap);
assertEquals("記入に誤りがあります", flashMap.get("errorMessage"));
}