Bird
0
0

Which of the following is the correct way to inject TestRestTemplate in a Spring Boot test class?

easy📝 Syntax Q3 of 15
Spring Boot - Testing Spring Boot Applications
Which of the following is the correct way to inject TestRestTemplate in a Spring Boot test class?
A@Autowired private TestRestTemplate restTemplate;
Bprivate TestRestTemplate restTemplate = new TestRestTemplate();
C@InjectMocks private TestRestTemplate restTemplate;
Dprivate TestRestTemplate restTemplate = TestRestTemplate.create();
Step-by-Step Solution
Solution:
  1. Step 1: Understand Spring Boot injection

    TestRestTemplate is a Spring bean in test context and should be injected with @Autowired.
  2. Step 2: Identify incorrect instantiations

    Direct new or factory methods are not used; @InjectMocks is for Mockito, not Spring injection.
  3. Final Answer:

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

    Inject TestRestTemplate with @Autowired [OK]
Quick Trick: Always use @Autowired to inject TestRestTemplate in tests [OK]
Common Mistakes:
  • Creating TestRestTemplate manually instead of injecting
  • Using Mockito annotations incorrectly
  • Calling non-existent factory methods

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes