sandrowi
sandrowi

Reputation: 113

Sprint TestRestTemplate returns Id null

I have an integration test for a Spring Application which uses the TestRestTemplate to make requests. Everytime I make a request, the template returns an entity but the id is always null. If I do the same via Postman, the id is not null so I must have something to do with the test itself but I don't know what it is. Does anyone have an idea?

The Test looks like this:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebIntegrationTest(randomPort = true)
public class GameServiceControllerIT {
    @Value("${local.server.port}")
    private int port;

    private URL base;
    private RestTemplate template;

    @Before
    public void setUp()
            throws Exception {
        this.base = new URL("http://localhost:" + port + "/");
        this.template = new TestRestTemplate();
    }

    @Test
    public void testAddGame() {
        User user = addUser();
        ResponseEntity<Game> gameEntity = template.exchange(base + "/games/new?token=" + user.getToken(), HttpMethod.POST, null, Game.class);

        Assert.assertThat(gameEntity.getStatusCode(), is(HttpStatus.OK));               //This works
        Assert.assertThat(gameEntity.getBody().getOwner(), is(user.getUsername()));     //This works too
        Assert.assertThat(gameEntity.getBody().getId(), is(not(null)));                 //This doesn't work
    }

The API endpoint looks like this:

@RequestMapping(value = CONTEXT + "/new", method = RequestMethod.POST)
@ResponseBody
@JsonView(Views.Public.class)
public ResponseEntity<Game> createGame(@RequestParam("token") String token) {

    Game game = new Game();
    User owner = userRepo.findByToken(token);

    if (owner == null) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    if (!UserUtils.isInOpenGame(owner)) {
        owner.setCharacterType(CharacterType.CHEYENNE);
        game.setOwner(owner.getUsername());
        game.setStatus(GameStatus.PENDING);
        game.setCurrentPlayer(0);
        game.getPlayers().add(owner);
        game = gameRepo.save(game);

        logger.info("Game " + game.getId() + " successfully created");
        return ResponseEntity.ok(game);
    } else if (owner.getGames().size() > 0) {
        logger.info("User already created or joined a game");
        return new ResponseEntity<>(HttpStatus.PRECONDITION_REQUIRED);
    } else {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

Upvotes: 0

Views: 908

Answers (1)

hernandezjd
hernandezjd

Reputation: 59

I found the same issue. Somehow the "Id" field has some meaning for RestTemplate, so it becomes "reserved". If you have access to the server generating the response, just change the name of the field to "Iid", for instance, in the Game class. The getter getId() has to be renamed to getIid().

Upvotes: 1

Related Questions