gpt4 book ai didi

java - Sprint TestRestTemplate 返回 Id null

转载 作者:行者123 更新时间:2023-12-01 10:03:05 27 4
gpt4 key购买 nike

我有一个 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);
}
}

最佳答案

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

关于java - Sprint TestRestTemplate 返回 Id null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36664209/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com