Java mockito void methods

Mock Void method with Mockito

Hey guys! After our previous blog on difference between thenReturn and thenAnswer mockito methods, we are back with yet another interesting blog on Mockito. Here, we shall discuss «How to Mock Void method with Mockito». Let’s get started!

When writing code, there is always at least one method that returns ‘void’, and at some point in time we need to mock ‘void’ method. So how do we go about it? Let us together figure this out in the following blog using mockito.

Mockito is one of the most famous mocking framework used for writing unit tests. If you are new to mocking you can know more at mockito website.

In this blog we will cover,

Why we need to mock void method?

Let’s assume we have a method. In this method we call another void method. Now, when you want to write test case for this method, how can we test that the void method was called? Also, if the correct parameters were passed to void method?
In this case mockito comes to our rescue.

Читайте также:  Сокращение числа в python

Let’s take an example, we have a UserService class. In this class we have a updateName() method.

Now, we want to write unit test for UserService class and mock userRepository.
But the only thing we need to verify in this test case is that updateName() method from userRepository is called with correct set of parameters.
For this purpose we need to mock updateName() method, capture the arguments and verify the arguments.

One of the most important point to note here is that, we can not just mock void method using when-then mechanism of mockito. Because, when() method of mockito works with return value and does not work when method is void.

How to mock void method in mockito?

In Mockito we can use different methods to call real method or mock void method. We can use one of the options as per requirements

  1. doNothing() : Completely ignore the calling of void method, this is default behavior
  2. doAnswer() : Perform some run time or complex operations when void method is called
  3. doThrow() : Throw exception when mocked void method is called
  4. doCallRealMethod() : Do not mock and call real method

1) Using doNothing()

If we just want to completely ignore the void method call, we can use doNothing().

In mocking, for every method of mocked object doNothing is the default behavior. Hence, if you don’t want to verify parameters, use of doNothing is completely optional. Following all codes perform similar behavior,

Example using doNothing() for void method

@Test public void testUpdateNameWithDoNothingVerifyRepositoryCall()

Without using doNothing() for void method

@Test public void testUpdateNameWithOutDoNothingVerifyRepositoryCall()

Example of argument capture using doNothing()

We can do different things with argument capture. Here, we will just verify the captured value

@Test public void testUpdateNameUsingArgumentCaptor() < ArgumentCaptoridCapture = ArgumentCaptor.forClass(Long.class); ArgumentCaptor nameCapture = ArgumentCaptor.forClass(String.class); doNothing().when(mockedUserRepository).updateName(idCapture.capture(),nameCapture.capture()); userService.updateName(1L,"void mock test"); assertEquals(1L, idCapture.getValue()); assertEquals("void mock test", nameCapture.getValue()); >

2) Using doAnswer() for void method

If we do not want to call real method, however need to perform some runtime operation doAnswer is used.

Let’s take an example of doAnswer where we will print and verify the argument using doAnswer

@Test public void testUpdateNameUsingDoAnswer() < doAnswer(invocation ->< long String name = invocation.getArgument(1); System.out.println("called for id: "+id+" and name: "+name); assertEquals(1L, id); assertEquals("void mock test", name); return null; >).when(mockedUserRepository).updateName(anyLong(),anyString()); userService.updateName(1L,"void mock test"); verify(mockedUserRepository, times(1)).updateName(1L,"void mock test"); >

3) Throw exception using doThrow()

If we want to throw an exception when method is called, we can use doThrow() method of mockito.

Let’s take an example where we will throw InvalidParamException when updateName() method is called with null id.

@Test(expected = InvalidParamException.class) public void testUpdateNameThrowExceptionWhenIdNull()

4) Real method call using doCallRealMethod()

Sometimes it is necessary to call the real method from mocked object, in such case we need to use doCallRealMethod(), because doNothig() is the default behavior.

In the following example real method from userRepository will be called even though it is a mocked object.

@Test public void testUpdateNameCallRealRepositoryMethod()

Fast track reading

  • Void method is mostly mocked to check if it is called with correct parameters
  • For mocking void method when-then mechanism of mockito does not work because it needs return value
  • Void methods can be handled using doNothing(), doAnswer(), doThrow() or doCallRealMethod()
  • doNothing() : Completely ignore the void method
  • doAnswer() : Perform some run time or complex operations
  • doThrow() : Throw exception when mocked void method is called
  • doCallRealMethod() : Do not mock and call real method
  • For mocked object doNothing is the default behavior for every method

Reference:

Источник

Mocking Void Methods with Mockito

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

In this short tutorial, we focus on mocking void methods with Mockito.

Further reading:

Mockito’s Java 8 Features

Mocking Exception Throwing using Mockito

As with other articles focused on the Mockito framework (such as Mockito Verify, Mockito When/Then, and Mockito’s Mock Methods), the MyList class shown below will be used as the collaborator in test cases.

We’ll add a new method for this tutorial:

public class MyList extends AbstractList  < @Override public void add(int index, String element) < // no-op >>

2. Simple Mocking and Verifying

Void methods can be used with Mockito’s doNothing(), doThrow(), and doAnswer() methods, making mocking and verifying intuitive:

@Test public void whenAddCalled_thenVerified()

However, doNothing() is Mockito’s default behavior for void methods.

This version of whenAddCalledVerified() accomplishes the same thing as the one above:

@Test void whenAddCalled_thenVerified()

doThrow() generates an exception:

@Test void givenNull_whenAddCalled_thenThrowsException() < MyList myList = mock(MyList.class); assertThrows(Exception.class, () ->< doThrow().when(myList).add(isA(Integer.class), isNull()); >); myList.add(0, null); >

We’ll cover doAnswer() below.

3. Argument Capture

One reason to override the default behavior with doNothing() is to capture arguments.

In the example above, we used the verify() method to check the arguments passed to add().

However, we may need to capture the arguments and do something more with them.

In these cases, we use doNothing() just as we did above, but with an ArgumentCaptor:

@Test void givenArgumentCaptor_whenAddCalled_thenValueCaptured() < MyList myList = mock(MyList.class); ArgumentCaptorvalueCapture = ArgumentCaptor.forClass(String.class); doNothing().when(myList).add(any(Integer.class), valueCapture.capture()); myList.add(0, "captured"); assertEquals("captured", valueCapture.getValue()); > 

4. Answering a Call to Void

A method may perform more complex behavior than merely adding or setting value.

For these situations, we can use Mockito’s Answer to add the behavior we need:

@Test void givenDoAnswer_whenAddCalled_thenAnswered() < MyList myList = mock(MyList.class); doAnswer(invocation ->< Object arg0 = invocation.getArgument(0); Object arg1 = invocation.getArgument(1); assertEquals(3, arg0); assertEquals("answer me", arg1); return null; >).when(myList).add(any(Integer.class), any(String.class)); myList.add(3, "answer me"); > 

As explained in Mockito’s Java 8 Features, we use a lambda with Answer to define custom behavior for add().

5. Partial Mocking

Partial mocks are an option too. Mockito’s doCallRealMethod() can be used for void methods:

@Test void givenDoCallRealMethod_whenAddCalled_thenRealMethodCalled()

This way, we can call the actual method and verify it at the same time.

6. Conclusion

In this brief article, we covered four different ways to approach void methods when testing with Mockito.

As always, the examples are available in this GitHub project.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Оцените статью