问题
If there a way to disable @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
or @JsonIgnore
on testing?
I am trying to test my createUser()
but I need user.getPassword()
method be enabled when I parse my User
object.
If I comment the @JsonProperty
line it works but if that I do so, the password field will be returned on GET /users or GET /users/{id}
method.
Here is my test
@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())));
}
The method that create a new user:
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;
}
This is the json it got after serialize User
object with the ObjectMapper
:
{
"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 method
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity store(@Valid @RequestBody User user) {
userService.store(user);
return new ResponseEntity<Object>(user, HttpStatus.CREATED);
}
User.class property
@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;
Is it a workaround for this?
回答1:
You can disable all Jackson annotations by adding the following line:
objectMapper.disable(MapperFeature.USE_ANNOTATIONS);
For more info, you can check this link.
In your case, this should work:
@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())));
}
来源:https://stackoverflow.com/questions/42472525/how-to-disable-jsonproperty-or-jsonignore-on-test