Bird
0
0

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:
  1. Step 1: Identify correct HTTP method for creating resource

    POST is used to create new items, so postForEntity is appropriate.
  2. 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.
  3. Final Answer:

    Code snippet using postForEntity with POST and checking 201 and ID -> Option A
  4. 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes