You want to write a full integration test using TestRestTemplate that posts JSON data to /api/items and verifies the created item's ID is returned. Which code snippet correctly performs this test?
hard📝 state output Q15 of 15
Spring Boot - Testing Spring Boot Applications
You want to write a full integration test using TestRestTemplate that posts JSON data to /api/items and verifies the created item's ID is returned. Which code snippet correctly performs this test?
Avar item = new Item(null, "Book");
var response = restTemplate.postForEntity("/api/items", item, Item.class);
assertEquals(201, response.getStatusCodeValue());
assertNotNull(response.getBody().getId());
Bvar item = new Item(null, "Book");
var response = restTemplate.getForEntity("/api/items", Item.class);
assertEquals(201, response.getStatusCodeValue());
Cvar item = new Item(null, "Book");
var response = restTemplate.postForObject("/api/items", item, Item.class);
assertEquals(404, response.getStatusCodeValue());
Dvar item = new Item(null, "Book");
var response = restTemplate.exchange("/api/items", HttpMethod.GET, null, Item.class);
assertEquals(201, response.getStatusCodeValue());
Step-by-Step Solution
Solution:
Step 1: Identify correct HTTP method for creating resource
POST is used to create new items, so postForEntity is appropriate.
Step 2: Verify response status and body
201 status means created; response body should contain new item's ID, so assertNotNull on getId() is correct.
Final Answer:
Code snippet using postForEntity with POST and checking 201 and ID -> Option A
Quick Check:
POST + 201 + returned ID = correct test [OK]
Quick Trick:Use postForEntity and check 201 plus returned ID [OK]
Common Mistakes:
Using GET instead of POST for creation
Expecting 404 instead of 201 status
Using postForObject without status check
Master "Testing Spring Boot Applications" in Spring Boot
9 interactive learning modes - each teaches the same concept differently