0
0
JUnittesting~10 mins

TestRestTemplate for API testing in JUnit - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a TestRestTemplate instance.

JUnit
TestRestTemplate restTemplate = new [1]();
Drag options to blanks, or click blank then click option'
ATestRestTemplate
BRestTemplate
CHttpClient
DWebClient
Attempts:
3 left
💡 Hint
Common Mistakes
Using RestTemplate instead of TestRestTemplate.
Using HttpClient or WebClient which are not part of Spring Boot test utilities.
2fill in blank
medium

Complete the code to send a GET request to '/api/users' and get the response as a String.

JUnit
ResponseEntity<String> response = restTemplate.[1]("/api/users", String.class);
Drag options to blanks, or click blank then click option'
ApostForEntity
Bexchange
Cdelete
DgetForEntity
Attempts:
3 left
💡 Hint
Common Mistakes
Using postForEntity which sends a POST request.
Using delete which sends a DELETE request.
Using exchange without specifying HTTP method.
3fill in blank
hard

Fix the error in the assertion to check if the response status code is 200 OK.

JUnit
assertEquals(HttpStatus.[1], response.getStatusCode());
Drag options to blanks, or click blank then click option'
AOK
BNOT_FOUND
CBAD_REQUEST
DCREATED
Attempts:
3 left
💡 Hint
Common Mistakes
Using NOT_FOUND (404) or BAD_REQUEST (400) which indicate errors.
Using CREATED (201) which is for resource creation.
4fill in blank
hard

Fill both blanks to send a POST request with a User object and receive a User response.

JUnit
ResponseEntity<User> response = restTemplate.[1]("/api/users", [2], User.class);
Drag options to blanks, or click blank then click option'
ApostForEntity
BgetForEntity
Cnew User("John", "john@example.com")
Dnull
Attempts:
3 left
💡 Hint
Common Mistakes
Using getForEntity for POST requests.
Passing null instead of a User object.
5fill in blank
hard

Fill all three blanks to assert the response body has the expected user's email.

JUnit
assertTrue(response.getBody().[1]().[2]("[3]"));
Drag options to blanks, or click blank then click option'
AgetEmail
Bequals
Cjohn@example.com
DtoString
Attempts:
3 left
💡 Hint
Common Mistakes
Using toString instead of getEmail.
Using '==' instead of equals for string comparison.
Using wrong field name.