2012-09-26 57 views
1

你好我下面一個例子,我發現Hibernate的驗證沒有驗證

http://www.mkyong.com/spring-mvc/spring-3-mvc-and-jsr303-valid-example/ 

的問題是沒有錯誤在我的個人資料,我發現後。我應該。爲什麼會發生這種情況?

@Test 
@Ignore 
public void anotherTest() { 
    Profile profile = ProfileUtil.getProfile(); 

    profile.setEmail("[email protected]"); 
    profile.setSex("dafjsgkkdsfa"); 
    BindingResult bindingResult = new BeanPropertyBindingResult(profile, "profile"); 
    userController.postUser(new ModelMap(), profile, bindingResult); 

    if (bindingResult.hasErrors()) { 
     System.out.println("errors"); 
    } 

    assertTrue(bindingResult.hasErrors()); 

    profileService.deleteProfile(profile); 
} 


@RequestMapping(value = "/", method = RequestMethod.POST) 
public View postUser(ModelMap data, @Valid Profile profile, BindingResult bindingResult) { 

     if (bindingResult.hasErrors()) { 
      System.out.println("No errors"); 
      return dummyDataView; 
     } 

     data.put(DummyDataView.DATA_TO_SEND, "users/user-1.json"); 
     profileService.save(profile); 
     return dummyDataView; 
} 

編輯: 這是配置文件。我現在正在測試性行爲,所以我認爲這很重要。

package no.tine.web.tinetips.domain; 

import java.util.Date; 

import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.Id; 
import javax.persistence.Temporal; 
import javax.persistence.TemporalType; 
import javax.validation.constraints.Max; 
import javax.validation.constraints.Min; 
import javax.validation.constraints.NotNull; 
import javax.validation.constraints.Pattern; 
import javax.validation.constraints.Size; 

import no.tine.web.tinetips.util.CommonRegularExpressions; 

import org.hibernate.validator.constraints.NotBlank; 


@Entity 
public class Profile { 

    @Id 
    @GeneratedValue 
    private Long id; 

    @NotNull(message = "profile.email.null") 
    @NotBlank(message = "profile.email.blank") 
    @Size(max = 60, message = "profile.email.maxlength") 
    @Pattern(regexp = CommonRegularExpressions.EMAIL, message = "profile.email.regex") 
    @Column(name = "Email", unique = true) 
    private String email; 

    @Pattern(regexp = "^[M|F]{1}$", message = "profile.sex.regex") 
@Size(max = 1, message = "profile.sex.maxlength") 
private String sex; 


} 
+0

顯示您的個人檔案類源 – vacuum

回答

1

基本上你實例化的POJO與this.userController = new UserController(),調用其方法this.controller.postUser(...)。只是簡單的Java對象,與Spring和Spring MVC沒有任何關係:@Valid沒有考慮在內。

如果你想使它工作,你將不得不給你的測試類一些春季信息,@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(...)。然後,對於Spring MVC部分,您將不得不通過一些Spring MVC設備在您的Controller上嘲諷請求調用。如果你使用Spring MVC 3.0或3.1+,它的做法會有所不同。例如,有關更多信息和實際代碼,請參見see this post and its answers

+0

我正在使用@ContextConfiguration(...)和@RunWith(SpringJUnit4ClassRunner.class)。我的控制器現在不接受任何請求。也許我應該改變這一點。 – pethel

+0

@ user874774控制器本身很好,它是你在你的單元測試中不起作用的。你不能只是'this.controller.postUser(...)'。查看我給你的鏈接,知道如何調用它。 –

+0

我在哪裏可以找到框架的jar。對GIT中心站點的依賴不能得到解決。 – pethel