【问题标题】:Sprint TestRestTemplate returns Id nullSprint TestRestTemplate 返回 Id null
【发布时间】:2016-04-16 12:30:29
【问题描述】:

我有一个 Spring 应用程序的集成测试,它使用 TestRestTemplate 发出请求。每次我发出请求时,模板都会返回一个实体,但 id 始终为空。如果我通过 Postman 执行相同操作,则 id 不为空,因此我必须与测试本身有关,但我不知道它是什么。有人有想法吗?

测试看起来像这样:

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

API 端点如下所示:

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

【问题讨论】:

    标签: java spring rest spring-boot integration-testing


    【解决方案1】:

    我发现了同样的问题。不知何故,“Id”字段对 RestTemplate 有一些意义,所以它变成了“保留”。如果您有权访问生成响应的服务器,只需将字段名称更改为“Iid”,例如在 Game 类中。 getter getId() 必须重命名为 getIid()。

    【讨论】:

      猜你喜欢
      • 2021-05-17
      • 2019-06-16
      • 1970-01-01
      • 2014-12-26
      • 2019-02-02
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      相关资源
      最近更新 更多