Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Methods of Mockito

Mockito provides the necessary tools to simplify your testing process and improve the quality of your code. By mastering the methods of Mockito, you will gain confidence in writing effective tests, ensuring the correctness and stability of your software.

Learn Java and become a professional developer. This Java course will give you the skills you need to land a job as a Java developer!

Mockito ‘mock()’ Method

The ‘mock()’ method in Mockito is used to create mock objects of classes or interfaces. Mockito provides five variations of the ‘mock()’ method, each with different parameters. These methods serve the same purpose of creating mock objects, which are objects that simulate the behavior of real objects.

Here are the different variations of the ‘mock()’ method:

  • mock(Class classToMock): This method creates mock objects of a specific class or interface. It takes the class or interface name as a parameter.
  • mock(Class classToMock, Answer defaultAnswer): This advanced method creates mock objects with specific behavior. This can prove useful when working with legacy systems. The ‘Answer’ parameter allows you to define custom responses for method invocations on the mock object.
  • mock(Class classToMock, MockSettings mockSettings): Mock objects are created with non-standard settings using this method. It takes an additional ‘MockSettings’ parameter along with the class or interface name. MockSettings allows you to configure various settings for the mock object.
  • mock(Class classToMock, ReturnValues returnValues): With this method, one can create mock objects with specific behaviors. However, the use of this method has now depreciated, and instead, using the ‘Answer’ parameter is recommended.
  • mock(Class classToMock, String name): This method creates mock objects and allows you to specify a name for the mock. Naming mock objects can be helpful for debugging purposes, especially when dealing with complex codebases.

This sample code snippet demonstrates the usage of the ‘mock()’ method: 

ToDoService doService = mock(ToDoService.class);

Learn Java from scratch with our beginner-friendly Java tutorial. No prior programming experience is necessary!

Mockito ‘when()’ Method

The ‘when()’ method in Mockito enables the stubbing of methods. It allows us to specify the behavior of a mock object when certain methods are called. It follows the pattern: “When a specific method is called, then return a specific value.” This is particularly useful when defining different behaviors based on certain conditions during testing.

Syntax:

 when(T methodCall)

This sample code snippet demonstrates the usage of the when() method:

when(mock.someCode()).thenReturn(5);

In the above code, the ‘when()’ method is used to specify the behavior of the ‘someCode()’ method on the mock object. It is configured to return 5 when the ‘someCode()’ method is called.

Typically, the ‘thenReturn()’ method is used with the ‘when()’ method. It specifies the value that must be returned when a corresponding method is called.

Mockito ‘verify()’ Method

The ‘verify()’ method in Mockito verifies whether specific methods have been called during a test. It allows us to validate the occurrence of expected behaviors in our code. This method is typically used at the end of a test to ensure that the defined methods have been invoked as intended.

When we mock objects using Mockito, the framework keeps track of all the method calls and their parameters. We can then use the ‘verify()’ method to check if the expected conditions, such as method invocations with specific parameters, have been met. This type of testing, focusing on method invocations rather than the result, is known as behavioral testing.

The ‘verify()’ method is also useful for testing the number of invocations. By utilizing various verification modes provided by Mockito, we can test if a method has been called exactly a certain number of times, at least once, or never.

There are two variations of the ‘verify()’ method available in the Mockito class, which are mentioned below:

  • verify(T mock): This method verifies that a specific behavior has occurred once. The ‘verify(T mock)’ method verifies whether the methods on the mocked object ‘mock’ have been called as expected.

Syntax:

 verify(T mock)
  • verify(T mock, VerificationMode mode): This method allows us to verify that a specific behavior has occurred according to a specified verification mode. The verification mode can verify the exact number of invocations, at least one invocation, or no invocations.

Syntax:

 verify(T mock, VerificationMode mode)

Mockito ‘spy()’ Method

Mockito provides a method called ‘spy()’ that allows us to mock an object partially. When using the ‘spy()’ method, we create a spy or stub of a real object. The spy method retains the real behavior of the object’s methods unless they are explicitly stubbed. This allows us to selectively override specific methods of the real object.

The ‘spy()’ method serves multiple functions, including the ability to verify the invocation of a particular method.

There are two variations of the ‘spy()’ method available in the Mockito class, which are mentioned below:

  • spy(T object): This method creates a spy of a real object. The spy retains the real behavior of the object’s methods unless they are stubbed. Using real spies judiciously and in specific cases, such as when dealing with legacy code, is important.

Syntax:

 spy(T object)
  • spy(Class classToSpy): This method creates a spy object based on a class instead of an existing object. It is particularly useful when spying on abstract classes that cannot be directly instantiated.

Syntax:

 spy(Class classToSpy)

This sample code snippet demonstrates the usage of the ‘spy()’ method:

List spyArrayList = spy(ArrayList.class);

Mockito ‘reset()’ Method

The ‘reset()’ method in Mockito resets mock objects. It is primarily used when working with container-injected mocks. However, avoiding the ‘reset()’ method is generally recommended, as it can result in lengthy code and poor test design. Instead, it is often better to create new mocks when necessary.

The ‘reset()’ method has the following signature:

public static  void reset(T... mocks) {
MOCKITO_CORE.reset(mocks);
}

Mockito ‘verifyNoMoreInteractions()’ Method

The ‘verifyNoMoreInteractions()’ method in Mockito checks that none of the specified mocks have unverified interactions. It is typically used after verifying all the necessary interactions with the mocks to ensure that no additional invocations have occurred.

This method is useful for detecting any unverified invocations that may have happened before the actual test method, such as in setup methods or constructors. It allows us to explicitly check that all expected interactions with the mocks have been verified.

The signature of the ‘verifyNoMoreInteractions()’ method is as follows:

public static void verifyNoMoreInteractions(Object... mocks) {
MOCKITO_CORE.verifyNoMoreInteractions(mocks);
}

Mockito ‘verifyZeroInteractions()’ Method

The ‘verifyZeroInteractions()’ method in Mockito is used to verify that no interactions have occurred on the specified mocks. It checks that none of the mock objects have been invoked during the test or before the test method, including invocations in setup methods, @Before methods, or constructors.

This method is helpful in ensuring that no unintended or unnecessary interactions have occurred with the mock objects.

The signature of the ‘verifyZeroInteractions()’ method is as follows:

public static void verifyZeroInteractions(Object... mocks) {
MOCKITO_CORE.verifyNoMoreInteractions(mocks);
}

Mockito ‘doThrow()’ Method

In Mockito, the ‘doThrow()’ method is employed to stub a void method to throw an exception. It allows the user to define the behavior of a void method such that it throws a specific exception when invoked. Two variations of the ‘doThrow()’ method are available in the Mockito class, each with different parameters. They are mentioned as follows:

  • ‘doThrow()’ method with Throwable: This variation is used when we want to stub a void method to throw a specific exception. We pass the exception instance as a parameter.

Syntax:

doThrow(Throwable toBeThrown)
The signature of the doThrow() method is as follows:
public static Stubber doThrow(Throwable toBeThrown) {
return MOCKITO_CORE.doAnswer(new ThrowsException(toBeThrown));
}
  • ‘doThrow()’ method with Class: This variation is used when we want to stub a void method to throw an exception for a specified class. We provide the exception class as a parameter.

Syntax:

doThrow(Class extends Throwable> toBeThrown)
The signature of the doThrow() method is as follows:
public static Stubber doThrow(Class extends Throwable> toBeThrown) {
return MOCKITO_CORE.doAnswer(new ThrowsExceptionClass(toBeThrown));
}

Mockito ‘doCallRealMethod()’ Method

The ‘doCallRealMethod()’ method in Mockito invokes the real implementation of a method. It is primarily used to create partial mocks of an object, where some methods are mocked while others are allowed to execute their actual implementation. This method is employed in rare situations when there is a need to call the real method.

The ‘doCallRealMethod()’ method is similar to the ‘spy()’ method but tends to produce more complex code. It is used when we want to partially mock an object and invoke the real methods for certain scenarios.

The signature of this method is mentioned below:

public static Stubber doCallRealMethod() {
return MOCKITO_CORE.doAnswer(new CallsRealMethods());
}

Mockito ‘doAnswer()’ Method

The ‘doAnswer()’ method in Mockito stubs a void method with a generic Answer type. It allows us to define a custom behavior or action when a mocked void method is called. The ‘doAnswer()’ method takes an instance of the Answer interface as a parameter, representing the logic or behavior to be executed when the method is invoked.

Here is the representation of the ‘doAnswer()’ method:

public static Stubber doAnswer(Answer answer) {
return MOCKITO_CORE.doAnswer(answer);
}

Mockito ‘doNothing()’ Method

The ‘doNothing()’ method is employed in rare situations. This method can be used for setting void methods to do nothing. The void methods on mock instances do nothing by default, i.e., no task is performed.

The signature of the ‘doNothing()’ method is as follows:

public static Stubber doNothing() {
return MOCKITO_CORE.doAnswer(new DoesNothing());
}

Mockito ‘doReturn()’ Method

The ‘doReturn()’ method in Mockito is used in special cases when the ‘Mockito.when(object)’ method cannot be used. It provides an alternative way to stub method invocations on mock objects. However, it is generally recommended to use the ‘Mockito.when(object)’ method for stubbing, as it is type-safe and more readable.

The representation of this method is as follows:

public static Stubber doReturn(Object toBeReturned) {
return MOCKITO_CORE.doAnswer(new Returns(toBeReturned));
}

Mockito ‘inOrder()’ Method

The ‘inOrder()’ method in Mockito generates objects that facilitate the verification of mocks in a specific sequence. Conducting verification in a predetermined order offers increased flexibility, as it allows us to focus solely on the interactions we are interested in testing, disregarding the rest. By employing the ‘inOrder()’ method, we can create an ‘inOrder’ object by passing the relevant mocks that need to be verified in order.

The representation of this method is as follows:

public static InOrder inOrder(Object... mocks) {
return MOCKITO_CORE.inOrder(mocks);
}

Mockito ‘ignoreStubs()’ Method

The ‘ignoreStubs()’ method in Mockito is employed to disregard the stubbed methods of specified mocks during verification. This method is particularly useful when used in conjunction with the ‘verifyNoMoreInteractions()’ or ‘verification inOrder()’ methods. Ignoring the stubbed calls helps eliminate redundant verification and ensures a more focused and concise testing approach.

Here is the representation of the ‘ignoreStubs()’ method:

public static Object[] ignoreStubs(Object... mocks) {
return MOCKITO_CORE.ignoreStubs(mocks);
}

Mockito ‘times()’ Method

The ‘times()’ method in Mockito is utilized to verify a method’s exact number of invocations. It allows us to declare the number of times a method should be invoked during testing. This method helps ensure that the expected behavior is correctly executed and the desired interactions occur as intended.

The representation of this method is as follows:

public static VerificationMode times(int wantedNumberOfInvocations) {
return VerificationModeFactory.times(wantedNumberOfInvocations);
}

Mockito ‘never()’ Method

The ‘never()’ method in Mockito is employed to verify that a particular interaction did not occur during the test. It allows us to assert that a method was never invoked in the code that is under test. This is particularly useful when we want to ensure that certain actions or behaviors do not take place.

Here is the representation of the ‘never()’ method:

public static VerificationMode never() {
return times(0);
}

Mockito ‘atLeast()’ Method

The ‘atLeast()’ method in Mockito is employed to verify that a specific method is invoked a minimum number of times during the test. This verification mode allows us to ascertain that a method is called at least several times, ensuring that the expected behavior occurs consistently.

Here is the representation of the ‘atLeast()’ method:

public static VerificationMode atLeast(int minNumberOfInvocations) {
return VerificationModeFactory.atLeast(minNumberOfInvocations);
}

Mockito ‘atMost()’ Method

The ‘atMost()’ method in Mockito is utilized to verify that a specific method is invoked at most a certain number of times during the test. This verification mode allows us to assert that a method is called at most several times, ensuring that the expected behavior is not exceeded.

Here is the representation of the ‘atMost()’ method:

public static VerificationMode atMost(int maxNumberOfInvocations) {
return VerificationModeFactory.atMost(maxNumberOfInvocations);
}

Mockito ‘calls()’ Method

The ‘calls()’ method in Mockito enables non-greedy verification in a specific order. It is used in conjunction with the ‘inOrder()’ verification method to specify the exact number of invocations expected for a particular method.

The representation of this method is as follows:

public static VerificationMode calls(int wantedNumberOfInvocations) {
return VerificationModeFactory.calls(wantedNumberOfInvocations);
}

Mockito ‘only()’ Method

The ‘only()’ method in Mockito is used to verify that a specific method is the only one invoked during a test. It ensures that no other methods are called on the given mock object.

The representation of this method is as follows:

public static VerificationMode only() {
return VerificationModeFactory.only();
}

Mockito ‘validateMockitoUsage()’ Method

The ‘validateMockitoUsage()’ method in Mockito is utilized to explicitly validate the state of the Mockito framework and identify any invalid usage. This method serves as an optional feature in Mockito, continuously validating its usage.

Career Transition


After each test method, the ‘validateMockitoUsage()’ method gets automatically invoked by ‘MockitoJUnitRunner,’ which is the built-in runner, and the ‘MockitoRule’ rule. This automatic invocation ensures that the Mockito framework is correctly utilized such that it detects potential misuse.

The representation of this method is as follows:

public static void validateMockitoUsage() {
MOCKITO_CORE.validateMockitoUsage();
}

Mockito ‘withSettings()’ Method

The ‘withSettings()’ method in Mockito serves the purpose of creating mock objects with additional settings. It is advised to use this method sparingly in testing scenarios. Instead, it is recommended to create straightforward tests using simple mocks. However, there are certain situations where the use of MockSettings becomes advantageous, some of which are mentioned below:

  • Flexibility: With MockSettings, it becomes easier to incorporate other mock settings as and when required.
  • Code Organization: The withSettings() method allows for the seamless combination of different mock settings without introducing code complexity or confusion.

Mentioned below is the representation of the ‘withSettings()’ method:

public static MockSettings withSettings() {
return new MockSettingsImpl().defaultAnswer(RETURNS_DEFAULTS);
}

The post Methods of Mockito appeared first on Intellipaat Blog.



This post first appeared on What Is DevOps, please read the originial post: here

Share the post

Methods of Mockito

×

Subscribe to What Is Devops

Get updates delivered right to your inbox!

Thank you for your subscription

×