Return to site

🍃🎓 SPRING CERTIFICATION QUESTION: Mocking

· spring,vcp,java

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

* @Mock

* @MockBean

* @Inject

* @InjectMocks

#spring #certificationquestion #vcp

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.