samedi 10 juin 2017

How to make @JsonView annotated Rest apis serializes all fields

I have a rest api like "/users/{userId}" This api returns User data but filters password with @JsonView(ResourceView.Public.class) annotation.

But I want to get password when the unit test runs. Is there a way to igore @JsonView annotation when test is running. Or any other options for me?

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;
    }
}

Aucun commentaire:

Enregistrer un commentaire