Monday, August 31, 2020

Mockito

 Mockito is a mocking framework. It is a Java-based library used to create simple and basic test APIs for performing unit testing of Java applications. It can also be used with other frameworks such as JUnit and TestNG.

The framework allows the creation of test double objects (mock objects) in automated unit tests for the purpose of test-driven development (TDD) or behavior-driven development (BDD).

Mockito allows developers to verify the behavior of the system under test (SUT) without establishing expectations beforehand.One of the criticisms of mock objects is that there is a tight coupling of the test code to the system under test.

Benefits of Mockito:

  • No Handwriting − No need to write mock objects on your own.
  • Refactoring Safe − Renaming interface method names or reordering parameters will not break the test code as Mocks are created at runtime.
  • Return value support − Supports return values.
  • Exception support − Supports exceptions.
  • Order check support − Supports check on order of method calls.
  • Annotation support − Supports creating mocks using annotation.

Following are the mock() methods with different parameters:

mock() method with Class: It is used to create mock objects of a concrete class or an interface. It takes a class or an interface name as a parameter.
Syntax: <T> mock(Class<T> classToMock)

mock() method with Answer: It is used to create mock objects of a class or interface with a specific procedure. It is an advanced mock method, which can be used when working with legacy systems. It takes Answer as a parameter along with the class or interface name. The Answer is an enumeration of pre-configured mock answers.
Syntax: <T> mock(Class<T> classToMock, Answer defaultAnswer)

mock() method with MockSettings: It is used to create mock objects with some non-standard settings. It takes MockSettings as an additional setting parameter along with the class or interface name. MockSettings allows the creation of mock objects with additional settings.
Syntax: <T> mock(Class<T> classToMock, MockSettings mockSettings)

mock() method with ReturnValues: It allows the creation of mock objects of a given class or interface. Now, it is deprecated, as ReturnValues are replaced with Answer.
Syntax: <T> mock(Class<T> classToMock, ReturnValues returnValues)

mock() method with String: It is used to create mock objects by specifying the mock names. In debugging, naming mock objects can be helpful whereas, it is a bad choice using with large and complex code.
Syntax: <T> mock(Class<T> classToMock, String name)


No comments:

Post a Comment

ES12 new Features