@Mock & @Injectmocks

Kyle_Kim·2024년 6월 23일
0

Mock Objects

Mock objects are simulated objects that mimic the behavior of real objects in a controlled way. They are used in unit testing to isolate the unit of code being tested from its dependencies, ensuring that the tests are focused solely on the behavior of the unit under test.

Benefits of Using Mock Objects:

  • Isolation: They isolate the unit of code from external dependencies.
  • Control: They allow you to define the behavior of dependencies in a predictable manner.
  • Performance: They are lightweight and faster than real objects, especially when the real objects involve I/O operations.
  • Simplification: They simplify testing by allowing you to simulate different scenarios and edge cases.

@Mock Annotation

The @Mock annotation is used in unit testing to create mock instances of classes. It is provided by mocking frameworks such as Mockito. When you annotate a field with @Mock, Mockito creates a mock instance of that field's type and injects it into the field.

@Mock
private SomeDependency someDependency;

@InjectMocks Annotation

The @InjectMocks annotation is used to automatically inject mock objects into the class instance that is being tested. This annotation is provided by Mockito and simplifies the setup of test scenarios where the class under test has dependencies that need to be mocked.

How It Works:

  • Mockito scans the class for dependencies (fields that can be injected).
  • It then looks for matching mock objects and injects them into the class.
profile
꾸준함.

0개의 댓글