使用TestRestTemplate的SpringBoot序列化问题

时间:2018-06-11 14:26:58

标签: jackson spring-boot-test

我有一个简单的Web控制器来返回用户实体 此实体具有无法更新的属性nonEditableProperty

它在Web控制器上运行正常,列出nonEditableProperty值,但在UserControllerTest上它不起作用,返回值始终为null

在测试序列化过程中,注释@JsonProperty(access = JsonProperty.Access.READ_ONLY)似乎被忽略了。

有没有人对此问题有任何线索?
我应该为测试加载一些Jackson配置吗?

@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");

        }
    }

1 个答案:

答案 0 :(得分:2)

iOS点击testRestTemplate.getForEntity(URI url, Class<T> responseType)获取api响应,然后将响应转换为url

指定的类型

虽然通过点击网址获取的API响应收到了responseType值(parse inputMessage.getBody here),但在将其反序列化为nonEditableProperty时,由于responseType Jackson属性,该值已丢失