Mock void methods in java

Mockito mock void method

In this post, we will look at how to mock void methods with Mockito. Methods that return void can’t be used with when. This means we have work with the following methods to mock a void method:

  • doThrow(Throwable. )
  • doThrow(Class)
  • doAnswer(Answer)
  • doNothing()
  • doCallRealMethod()

This is the class we will be using for the examples. It’s a small class with only one void method that prints “Hello, » followed by the input to the console.

class SomeClass void doAction(String name) System.out.println("Hello, " + name); > > 

Throwing an exception with a mocked void method

To make a void method throw an exception, we use doThrow() . The exception we pass to the doThrow() is thrown when the mocked method is called.

SomeClass mockInstance = mock(SomeClass.class); Mockito.doThrow(new RuntimeException()).when(mockInstance).doAction(anyString()); mockInstance.doAction("World!"); 

You can only use unchecked exceptions or exceptions that are declared in the method signature. The doThrow() call below wouldn’t work because IOException is a checked exception and not declared as part of the doAction() method signature.

Mockito.doThrow(new IOException()).when(mockInstance).doAction(anyString()); 

Verifying that a void method is called

With Mockito, we use verify() to check if a method has been called. The example below shows two ways of implementing this. times(1) is the default value, so you can omit it to have more readable code.

SomeClass mockInstance = mock(SomeClass.class); mockInstance.doAction("World!"); // using the default Mockito.verify(mockInstance).doAction(anyString()); // explicitly stating how many times a method is called Mockito.verify(mockInstance, times(1)).doAction(anyString()); 

Capturing void method arguments

We can also capture the arguments that we pass to a method. To do that we can create an ArgumentCaptor or use lambda matchers. Line 4 till 6 shows how to create and use the ArgumentCaptor . Lines 9 uses a lambda matcher. At line 11, we also use a lambda matcher, but with a method reference to keep it more readable.

SomeClass mockInstance = mock(SomeClass.class); mockInstance.doAction("World!"); ArgumentCaptorString> captor = ArgumentCaptor.forClass(String.class); Mockito.verify(mockInstance).doAction(captor.capture()); assertEquals("World!", captor.getValue()); // using lambda matchers verify(mockInstance).doAction(argThat(i -> "World!".equals(i))); // using lambda matchers with method reference verify(mockInstance).doAction(argThat("World!"::equals)); 

Stub a void method to run other code

We can also stub a method to let it perform other behavior. We use Mockito’s doAnswer() to change the behavior. The example below changed the message that gets printed to the console. The method will now print good morning instead of hello.

SomeClass mockInstance = mock(SomeClass.class); doAnswer(invocation ->  System.out.println("Good morning, " + invocation.getArgument(0)); return null; >).when(mockInstance).doAction(anyString()); mockInstance.doAction("World!"); 

Calling the real method

By default, stubbed will do nothing when you call them. To call the actual method, you can use doCallRealMethod() . Doing this will let you call the actual method of the class you mock.

SomeClass mockInstance = mock(SomeClass.class); doCallRealMethod().when(mockInstance).doAction(anyString()); mockInstance.doAction("World!"); 

Conclusion

In this post, we looked at the different ways of mocking void methods when you write tests using Mockito.

Источник

How to mock void methods with mockito in Java?

When writing unit tests, it is important to isolate the code under test to ensure that any failures are caused by the code under test and not by any dependencies. In Java, it is common to use mocking frameworks like Mockito to create mock objects that simulate the behavior of dependencies. However, it is not straightforward to mock void methods with Mockito, as they do not return a value that can be used for verification. Here are a few methods for mocking void methods with Mockito:

Method 1: Using the doNothing() method

Mockito is a popular mocking framework for Java. It allows you to mock objects and their methods, which is useful for testing your code. In this tutorial, we will show you how to mock void methods with Mockito using the doNothing() method.

Step 1: Add Mockito Dependency

First, you need to add the Mockito dependency to your project. You can do this by adding the following dependency to your pom.xml file:

dependency> groupId>org.mockitogroupId> artifactId>mockito-coreartifactId> version>3.7.7version> dependency>

Step 2: Create an Object to Mock

Next, you need to create an object to mock. In this example, we will create a UserService class with a void method deleteUser() :

public class UserService  public void deleteUser(String userId)  // delete user from database > >

Step 3: Create a Mock Object

Now, you can create a mock object for the UserService class using the Mockito.mock() method:

UserService userServiceMock = Mockito.mock(UserService.class);

Step 4: Mock the Void Method

To mock the deleteUser() method, you can use the doNothing() method:

Mockito.doNothing().when(userServiceMock).deleteUser(Mockito.anyString());

This tells Mockito to do nothing when the deleteUser() method is called with any string parameter.

Step 5: Test the Mock Object

Finally, you can test the mock object by calling the deleteUser() method:

userServiceMock.deleteUser("123");

Since we mocked the method to do nothing, this will not delete any user from the database.

Method 2: Using the doAnswer() method

Mockito is a popular Java mocking framework that allows developers to create mock objects for testing purposes. One of the common scenarios in testing is mocking void methods. In this tutorial, we will focus on mocking void methods using the doAnswer() method in Mockito.

Step 1: Add Mockito Dependency

To use Mockito in your Java project, you need to add the Mockito dependency to your build file. If you are using Maven, add the following dependency to your pom.xml file:

dependency> groupId>org.mockitogroupId> artifactId>mockito-coreartifactId> version>3.12.4version> scope>testscope> dependency>

Step 2: Create a Mock Object

To mock a void method, you need to create a mock object of the class that contains the void method. You can use the Mockito.mock() method to create a mock object. For example, let’s say we have a class called «MyClass» with a void method called «myVoidMethod». Here’s how you can create a mock object for this class:

MyClass myClassMock = Mockito.mock(MyClass.class);

Step 3: Mock the Void Method

To mock the void method using the doAnswer() method, you need to create an Answer object that defines the behavior of the method. The Answer object is responsible for executing the code when the mocked method is called. Here’s an example of how to use the doAnswer() method to mock the void method:

Mockito.doAnswer(new AnswerVoid>()  @Override public Void answer(InvocationOnMock invocation) throws Throwable  // Define the behavior of the method here return null; > >).when(myClassMock).myVoidMethod();

In this example, we are creating an Answer object that returns null when the mocked method is called. You can replace this code with any behavior that you want to test.

Step 4: Verify the Method Call

After mocking the void method, you can verify that it was called using the Mockito.verify() method. Here’s an example of how to verify the method call:

// Call the method myClassMock.myVoidMethod(); // Verify the method call Mockito.verify(myClassMock, Mockito.times(1)).myVoidMethod();

In this example, we are calling the mocked method and then verifying that it was called once using the Mockito.verify() method.

Method 3: Using the doThrow() method

To mock void methods with Mockito using the doThrow() method, follow these steps:

MyClass myClassMock = mock(MyClass.class);
doThrow(new RuntimeException()).when(myClassMock).myVoidMethod();
myClassMock.myMethodThatCallsMyVoidMethod();
verify(myClassMock).myVoidMethod();

Here is a complete example:

import static org.mockito.Mockito.*; public class MyClassTest  @Test(expected = RuntimeException.class) public void testMyVoidMethod()  MyClass myClassMock = mock(MyClass.class); doThrow(new RuntimeException()).when(myClassMock).myVoidMethod(); myClassMock.myMethodThatCallsMyVoidMethod(); verify(myClassMock).myVoidMethod(); > >

In this example, we are testing a method that calls myVoidMethod() from MyClass. We are mocking myVoidMethod() to throw a RuntimeException when it is called. We then call the method that should trigger myVoidMethod() and verify that it was called. The expected attribute in the @Test annotation is used to indicate that we expect a RuntimeException to be thrown when myVoidMethod() is called.

Источник

Методы Mocking Void с Mockito

В этом коротком руководстве мы сосредоточимся на имитации методовvoid с помощью Mockito.

Дальнейшее чтение:

Возможности Mockito Java 8

Обзор поддержки Java 8 в инфраструктуре Mockito, включая потоки и методы интерфейса по умолчанию

Насмешливое Бросание Исключений с использованием Мокито

Научитесь настраивать вызов метода для выдачи исключения в Mockito.

Как и в других статьях, посвященных фреймворку Mockito (например,Mockito Verify,Mockito When/Then иMockito’s Mock Methods), показанный ниже классMyList будет использоваться в качестве соавтора в тестовых примерах. Мы добавим новый метод для этого урока:

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

2. Простая фиксация и проверка

МетодыVoid можно использовать с методамиdoNothing(), doThrow(), and doAnswer() Mockito, что делает насмешку и проверку интуитивно понятными:

@Test public void whenAddCalledVerified()

ОднакоdoNothing() — это поведение Mockito по умолчанию для методов void.

Эта версияwhenAddCalledVerified() выполняет то же самое, что и предыдущая:

@Test public void whenAddCalledVerified()

DoThrow() генерирует исключение:

@Test(expected = Exception.class) public void givenNull_AddThrows()

Мы рассмотримdoAnswer() ниже.

3. Захват аргумента

Одна из причин переопределить поведение по умолчанию с помощьюdoNothing() — это захват аргументов.

В приведенном выше примереverify() используется для проверки аргументов, переданныхadd().

Тем не менее, нам может потребоваться зафиксировать аргументы и сделать с ними что-то большее. В этих случаях мы используемdoNothing() так же, как и выше, но сArgumentCaptor:

@Test public void whenAddCalledValueCaptured()

4. Ответ на вызовVoid

Метод может выполнять более сложное поведение, чем просто добавление или установка значения. В этих ситуациях мы можем использовать MockitoAnswer, чтобы добавить необходимое нам поведение:

@Test public void whenAddCalledAnswered() < MyList myList = mock(MyList.class); doAnswer((Answer) 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"); >

Как объяснено вMockito’s Java 8 Features, мы используем лямбда сAnswer для определения пользовательского поведения дляadd().

5. Частичное издевательство

Частичные насмешки тоже возможны. Mockito’sdoCallRealMethod() можно использовать для методовvoid:

@Test public void whenAddCalledRealMethodCalled()

Это позволяет нам вызвать фактический вызываемый метод и одновременно проверить его.

6. Заключение

В этом кратком руководстве мы рассмотрели четыре различных подхода к методамvoid при тестировании с помощью Mockito.

Как всегда, примеры доступны вthis GitHub project.

Источник

Читайте также:  Checking value in array java
Оцените статью