如何使@JsonView注释Rest apis序列化所有字段

时间:2017-06-10 13:16:52

标签: json spring testing jackson

我有一个像#34; / users / {userId}" 此api返回用户数据,但通过@JsonView(ResourceView.Public.class)注释过滤掉密码。

但我想在单元测试运行时获取密码。 有没有办法在测试运行时使用@JsonView注释。 或者对我来说还有其他选择吗?

public class ResourceView {
    public interface Public {}
    public interface Friends extends Public {}
    public interface Family extends Friends {}
}

public class User {
    @JsonView(ResourceView.Public.class)
    private String name;

    @JsonView(ResourceView.Family.class)
    private String password;
}

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @JsonView(ResourceView.Public.class)
    @GetMapping(value = "/users/{userId}")
    public User getUser(@PathVariable("userId") String userId) {
    return userService.getUser(userId);
    }
}

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles(profiles = "test")
public class UserServiceTest {

    @Autowired
    protected TestRestTemplate restTemplate;

    @Value("${local.server.port}")
    private int port;

    protected String apiEndpoint;

    @Before
    protected void setUp() {
    initRequestContext();
    apiEndpoint = "http://localhost:" + port;
    }

    protected ResponseEntity<User> requestGetUser(String userId) {
    ResponseEntity<User> res = restTemplate.exchange(
        apiEndpoint + "/users/" + userId,
        HttpMethod.GET,
        new HttpEntity<>("parameters", createDefaultHttpHeaders()),
        new ParameterizedTypeReference<User>() {});

    return res;
    }

    @Test
    public void testGetUser() throws Exception {
    ResponseEntity<User> apiRes = requestGetUsers(request);
    assertThat(apiRes.getStatusCode(), is(HttpStatus.OK));
    User user = apiRes.getBody();
    assertThat(user.getName(), is(notNullValue()));
    assertThat(user.getPassword(), is(notNullValue()));
    }
}

@Configuration
public class MyConfig {
    @Bean
    public ObjectMapper objectMapper() {
    ObjectMapper objectMapper = new ObjectMapper().configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
    return objectMapper;
    }
}

0 个答案:

没有答案