Bird
Raised Fist0
JUnittesting~20 mins

TestRestTemplate for API testing in JUnit - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
TestRestTemplate Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the test result of this TestRestTemplate GET request?
Consider this JUnit test using TestRestTemplate to call a REST API endpoint that returns a JSON with a message.
What will be the value of response.getBody() after this test runs?
JUnit
ResponseEntity<String> response = testRestTemplate.getForEntity("/api/greet", String.class);
String body = response.getBody();
A"{message:Hello World}"
Bnull
C"Hello World"
D"{\"message\":\"Hello World\"}"
Attempts:
2 left
💡 Hint
The API returns a JSON string with a message field.
❓ assertion
intermediate
2:00remaining
Which assertion correctly verifies the HTTP status code 200?
You want to check that the response status code from TestRestTemplate is HTTP 200 OK.
Which assertion is correct in JUnit 5?
JUnit
ResponseEntity<String> response = testRestTemplate.getForEntity("/api/data", String.class);
AassertEquals(HttpStatus.OK, response.getStatusCode());
BassertTrue(response.getStatusCode() == 200);
CassertEquals(200, response.getStatusCodeValue());
DassertEquals("200", response.getStatusCode().toString());
Attempts:
2 left
💡 Hint
HttpStatus.OK is an enum constant representing 200.
❓ locator
advanced
2:00remaining
Which URI template is correct for a path variable in TestRestTemplate?
You want to call an API endpoint with a path variable userId using TestRestTemplate.
Which URI template and call is correct?
AtestRestTemplate.getForEntity("/users/:userId", String.class, 42);
BtestRestTemplate.getForEntity("/users/{userId}", String.class, 42);
CtestRestTemplate.getForEntity("/users/$userId", String.class, 42);
DtestRestTemplate.getForEntity("/users/?userId=42", String.class);
Attempts:
2 left
💡 Hint
TestRestTemplate uses curly braces {} for path variables.
🔧 Debug
advanced
2:00remaining
Why does this POST request test fail with 415 Unsupported Media Type?
This test sends a POST request with a JSON body but fails with HTTP 415 error.
What is the likely cause?
JUnit
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>("{\"name\":\"Test\"}", headers);
ResponseEntity<String> response = testRestTemplate.postForEntity("/api/users", request, String.class);
AThe HttpEntity is missing the Accept header.
BThe JSON string is malformed and causes parsing error.
CThe server expects a different Content-Type header than application/json.
DThe testRestTemplate instance is not initialized properly.
Attempts:
2 left
💡 Hint
415 means the server does not support the media type sent.
❓ framework
expert
3:00remaining
How to configure TestRestTemplate to use Basic Authentication in a Spring Boot test?
You want to test a secured API endpoint that requires Basic Auth using TestRestTemplate.
Which code snippet correctly configures TestRestTemplate with username 'user' and password 'pass'?
ATestRestTemplate testRestTemplate = new TestRestTemplate("user", "pass");
B
TestRestTemplate testRestTemplate = new TestRestTemplate();
testRestTemplate.getRestTemplate().getInterceptors().add(new BasicAuthenticationInterceptor("user", "pass"));
C
TestRestTemplate testRestTemplate = new TestRestTemplate();
testRestTemplate.setBasicAuth("user", "pass");
D
TestRestTemplate testRestTemplate = new TestRestTemplate();
testRestTemplate.getRestTemplate().setBasicAuth("user", "pass");
Attempts:
2 left
💡 Hint
TestRestTemplate has a constructor that accepts username and password.

Practice

(1/5)
1. What is the primary purpose of TestRestTemplate in JUnit testing?
easy
A. To mock database connections during tests
B. To send real HTTP requests to test REST APIs
C. To generate random test data for unit tests
D. To create UI components for testing

Solution

  1. Step 1: Understand the role of TestRestTemplate

    TestRestTemplate is designed to send actual HTTP requests to REST APIs during integration tests.
  2. Step 2: Compare with other options

    Mocking databases, generating test data, or creating UI components are unrelated to TestRestTemplate's purpose.
  3. Final Answer:

    To send real HTTP requests to test REST APIs -> Option B
  4. Quick Check:

    TestRestTemplate = Real HTTP requests [OK]
Hint: Remember: TestRestTemplate sends real HTTP calls [OK]
Common Mistakes:
  • Confusing TestRestTemplate with mocking tools
  • Thinking it generates test data
  • Assuming it tests UI components
2. Which of the following is the correct way to autowire TestRestTemplate in a Spring Boot test class?
easy
A. @Autowired private TestRestTemplate restTemplate;
B. private TestRestTemplate restTemplate = new TestRestTemplate();
C. @InjectMocks private TestRestTemplate restTemplate;
D. private TestRestTemplate restTemplate = null;

Solution

  1. Step 1: Identify correct Spring Boot injection

    In Spring Boot tests, @Autowired is used to inject TestRestTemplate automatically.
  2. Step 2: Evaluate other options

    Creating a new instance manually or using @InjectMocks is incorrect for TestRestTemplate injection in Spring Boot tests.
  3. Final Answer:

    @Autowired private TestRestTemplate restTemplate; -> Option A
  4. Quick Check:

    Use @Autowired for TestRestTemplate injection [OK]
Hint: Use @Autowired to inject TestRestTemplate [OK]
Common Mistakes:
  • Manually instantiating TestRestTemplate
  • Using @InjectMocks instead of @Autowired
  • Leaving the variable null without injection
3. Given the following test code snippet using TestRestTemplate:
ResponseEntity<String> response = restTemplate.getForEntity("/api/users/1", String.class);
int statusCode = response.getStatusCodeValue();
String body = response.getBody();
If the API returns HTTP 200 with body "User Found", what will be the values of statusCode and body?
medium
A. statusCode = 404, body = null
B. statusCode = 500, body = "Error"
C. statusCode = 200, body = "User Found"
D. statusCode = 200, body = null

Solution

  1. Step 1: Understand getForEntity behavior

    getForEntity sends a GET request and returns the full response including status and body.
  2. Step 2: Match API response to variables

    Since API returns 200 and "User Found", statusCode will be 200 and body will be "User Found".
  3. Final Answer:

    statusCode = 200, body = "User Found" -> Option C
  4. Quick Check:

    API 200 + body = statusCode 200 & body "User Found" [OK]
Hint: getForEntity returns status and body as received [OK]
Common Mistakes:
  • Assuming body is null on success
  • Confusing status codes with error codes
  • Ignoring response body content
4. Consider this test code using TestRestTemplate:
@Autowired
private TestRestTemplate restTemplate;

@Test
public void testGetUser() {
    ResponseEntity<String> response = restTemplate.getForEntity("/api/users/", String.class);
    assertEquals(200, response.getStatusCodeValue());
}
What is the likely problem with this test?
medium
A. The URL is missing a user ID, causing a 404 error
B. The assertion should check for 404 instead of 200
C. TestRestTemplate cannot be autowired
D. ResponseEntity<String> is not a valid return type

Solution

  1. Step 1: Analyze the request URL

    The URL "/api/users/" lacks a specific user ID, so the endpoint may not exist or return a list, not a single user.
  2. Step 2: Understand the assertion failure cause

    Expecting status 200 for a missing user ID endpoint may cause a 404 error, failing the test.
  3. Final Answer:

    The URL is missing a user ID, causing a 404 error -> Option A
  4. Quick Check:

    Missing ID in URL causes 404, not 200 [OK]
Hint: Check URL completeness before asserting status [OK]
Common Mistakes:
  • Assuming URL without ID returns 200
  • Wrong assertion status code
  • Thinking autowiring is the issue
5. You want to test a POST API endpoint /api/users that creates a user and returns HTTP 201 with the created user JSON. Which TestRestTemplate method and assertion combination correctly tests this?
hard
A. Use delete with user ID, then assert status 204
B. Use getForEntity with user ID, then assert status 200
C. Use exchange with GET method, then assert status 404
D. Use postForEntity with user object, then assert status 201 and response body contains user data

Solution

  1. Step 1: Identify correct HTTP method for creation

    POST is used to create resources, so postForEntity is appropriate for sending the user object.
  2. Step 2: Validate expected response and assertions

    The API returns 201 Created with user JSON, so assert status 201 and check response body contains user data.
  3. Final Answer:

    Use postForEntity with user object, then assert status 201 and response body contains user data -> Option D
  4. Quick Check:

    POST + postForEntity + assert 201 + check body [OK]
Hint: POST creation uses postForEntity and assert 201 [OK]
Common Mistakes:
  • Using GET instead of POST for creation
  • Asserting wrong status codes
  • Ignoring response body validation
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard