loomismilitia
loomismilitia

Reputation: 11

SpringBoot serialization issue using TestRestTemplate

I have a simple web controller to return an User entity.
This entity has a property nonEditableProperty that cannot be updated.

It's works fine on the web controller, the nonEditableProperty value is listed but on the UserControllerTest it doesn't work and the returned value is always null.

The annotation @JsonProperty(access = JsonProperty.Access.READ_ONLY) seems to be ignored during the test serialization.

Does anyone have any clue for this issue?
Should I load some Jackson configuration for the tests?

@Getter
@Entity
class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String name;

    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    private String nonEditableProperty;

    User() {
    }

    public User(String name, String nonEditableProperty) {
        this.name = name;
        this.nonEditableProperty = nonEditableProperty;
    }

}

@RestController
@AllArgsConstructor
@RequestMapping("users")
public class UserController {

    private final UserRepository userRepository;

    @GetMapping
    public Collection<User> getAllUsers() {
        return (Collection<User>) userRepository.findAll();
    }

    @GetMapping(path = "/{id}")
    public User getUser(@PathVariable Integer id) {
        return userRepository.findOne(id);
    }

}


@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerTest {

        @Autowired
        TestRestTemplate testRestTemplate;

        @Test
        public void getUserShouldReturnData() {

            ResponseEntity<User> response = testRestTemplate.getForEntity("/users/{id}", User.class, 1);
            assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);

            assertThat(response.getBody().getName()).isEqualTo("Muhammed Suiçmez");
            assertThat(response.getBody().getNonEditableProperty()).isEqualTo("Non editable property");

        }
    }

Upvotes: 1

Views: 551

Answers (1)

Sairam Cherupally
Sairam Cherupally

Reputation: 341

testRestTemplate.getForEntity(URI url, Class<T> responseType) Fetches the api response by hitting url and then converts response to the type given by responseType

Though the API response fetched by hitting URL received the nonEditableProperty value (parse inputMessage.getBody here), While deserializing it to responseType the value was lost, because of READ_ONLY Jackson property.

Upvotes: 2

Related Questions