我正在使用以下示例项目:
- JAX-RS(球衣 2)
- JSR-303 Bean 验证
- 泽西测试测试
- 灰熊 Http 容器
- 杰克逊 2.7.3
在添加 @JsonIgnore 和 @JsonProperty 之前,一切都按预期工作,我能够在对我的对象属性执行 bean 验证时毫无问题地运行我的测试。通常“密码”字段不应该可用于反序列化,所以我用@JsonIgnore 标记它的getter,用@JsonProperty 标记它的setter,以便在保存新帐户对象时允许序列化它。
启动测试时,我收到 400 代码错误,并显示以下 http 响应结果:
avr. 26, 2016 12:25:29 PM org.glassfish.jersey.filter.LoggingFilter log
INFO: 1 * Client response received on thread main
1 < 400
1 < Connection: close
1 < Content-Length: 172
1 < Content-Type: application/json
1 < Date: Tue, 26 Apr 2016 11:25:29 GMT
1 < Vary: Accept
[{"message":"may not be null","messageTemplate":"{javax.validation.constraints.NotNull.message}","path":"AccountEndpoint.saveAccount.account.password","invalidValue":null}]
注意:当删除@JsonIgnore 注解时,当然不会收到验证错误
我的资源:
@Path("/account")
public class AccountEndpoint {
@POST
@Path("/save/")
@Produces(MediaType.APPLICATION_JSON)
public Response saveAccount(@Valid Account account){
Account returned = accountService.saveAccount(account);
return Response.status(200).entity(returned).build();
}
我的 Pojo 课程:
public class Account implements Serializable {
private String username;
private String password;
// -- [username] ------------------------
@Size(max = 45)
@NotNull
@Column(name = "username", length = 45,unique=true)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@NotNull
@Size(max = 45)
@Column(name = "password", length = 45)
@JsonIgnore
public String getPassword() {
return password;
}
@JsonProperty
public void setPassword(String password) {
this.password = password;
}
}
我的单元测试:
public class AccountTest extends JerseyTest {
@Before
public void setUp() throws Exception {
super.setUp();
}
@After
public void after() throws Exception {
super.tearDown();
}
@Override
protected TestContainerFactory getTestContainerFactory() {
return new GrizzlyWebTestContainerFactory();
}
@Override
protected DeploymentContext configureDeployment() {
enable(TestProperties.LOG_TRAFFIC);
enable(TestProperties.DUMP_ENTITY);
return ServletDeploymentContext.forServlet(new ServletContainer(new
JerseyConfig()))
.contextParam("contextConfigLocation",TEST_APP_CONTEXT)
.addListener(org.springframework.web.context.ContextLoaderListener.class)
.servletPath("/").build();
}
@Test
public void testSave_New_User_Account {
Account account = new Account();
account.setUsername("Test");
account.setPassword("Test");
Response response = target("/account/save").request().
post(Entity.entity(account,MediaType.APPLICATION_JSON));
assertEquals(200, response.getStatus());
}
}
JeseyConfig 类:
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
packages("org.medel.endpoint");
}
}