Spring Certified Professional 2023 · Free Practice Question Easy

Question 19

Which of the following is an annotation that can be used to add mocks to a Spring ApplicationContext?

  • A

    @Mock

  • B

    @MockBean

  • C

    @Inject

  • D

    @InjectMocks

Reveal correct answer

Correct answer: B

Explanation

The correct annotation for adding mocks to a Spring ApplicationContext is @MockBean.


Let's break down each option:


@Mock: This annotation is not specific to Spring and is typically used with mocking frameworks like Mockito.

It is used to create a mock instance of a class or interface.


@MockBean: This is the correct annotation for adding mocks to a Spring ApplicationContext.

It is part of the Spring Testing support and is used to add a mock object to the Spring application context.

This is commonly used in integration tests where you want to replace a real bean with a mock.


@Inject: This annotation is part of the Java Dependency Injection (DI) specification.

It is not specifically related to creating mocks in a Spring ApplicationContext.

It is used for injecting dependencies into a class.


@InjectMocks: This annotation is used with the Mockito testing framework.

It is used to automatically inject mock or spy dependencies into the tested object.

However, it is not directly related to adding mocks to the Spring ApplicationContext.


In summary, the correct answer is @MockBean when you want to add mocks to a Spring ApplicationContext.

Discussion

Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need