如果有办法在测试时停用@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
或@JsonIgnore
?
我正在尝试测试createUser()
但我需要在解析user.getPassword()
对象时启用User
方法。
如果我对@JsonProperty
行发表评论,但如果我这样做,则会在GET /users or GET /users/{id}
方法上返回密码字段。
这是我的测试
@Test
public void createUser() throws Exception {
User user = UserFactory.newUser();
String userJson = objectMapper.writeValueAsString(user);
LOGGER.info("User to register: " + userJson);
mockMvc.perform(post("/users")
.content(userJson)
.contentType(contentType))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.id", is(notNullValue())));
}
创建新用户的方法:
public static User newUser() {
Fairy fairy = Fairy.create();
Person person = fairy.person();
User user = new User();
user.setName(person.getFirstName());
user.setLastName(person.getLastName());
user.setEmail(person.getEmail());
user.setUsername(person.getUsername());
user.setPassword(person.getPassword());
user.setSex(person.isMale() ? User.Sex.MALE : User.Sex.FEMALE);
user.setPhone(person.getTelephoneNumber());
user.setCountry(person.getAddress().getCity());
return user;
}
这是使用User
序列化ObjectMapper
对象后得到的json:
{
"createdAt" : null,
"updatedAt" : null,
"name" : "Jasmine",
"lastName" : "Neal",
"email" : "jasmineneal@yahoo.com",
"username" : "jasminen",
"sex" : "FEMALE",
"phone" : "321-104-989",
"country" : "San Francisco"
}
UserController.class方法
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity store(@Valid @RequestBody User user) {
userService.store(user);
return new ResponseEntity<Object>(user, HttpStatus.CREATED);
}
User.class属性
@Column(name = "password", length = 100)
@NotNull(message = "error.password.notnull")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY) // If I comment this, it works
private String password;
这是一种解决方法吗?
答案 0 :(得分:0)
您可以通过添加以下行来禁用所有Jackson注释:
objectMapper.disable(MapperFeature.USE_ANNOTATIONS);
有关更多信息,您可以检查此link。
在您的情况下,这应该可行:
@Test
public void createUser() throws Exception {
User user = UserFactory.newUser();
objectMapper.disable(MapperFeature.USE_ANNOTATIONS);
String userJson = objectMapper.writeValueAsString(user);
LOGGER.info("User to register: " + userJson);
mockMvc.perform(post("/users")
.content(userJson)
.contentType(contentType))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.id", is(notNullValue())));
}