Skip to main content

Posts

Showing posts from January, 2021

How to mock void methods with Mockito

How to mock void methods with Mockito while writing unit tests in Java? Some times the method you are unit testing, has a dependency on a method that does not return any value, but has a void return type. To mock such methods we can not use the `when-thenReturn` or `doReturn-when` pattern.  Our simple expectation from the `Void` dependency method could be that it throws an exception or does not perform any internal action. Mockito provides two constructs `doThrow-when` and `doNothing-when` to test the above scenarios. Mockito.doThrow(new Exception()).when(mockObject).methodName(); Mockito.doNothing().when(mockObject).methodName(); Let's look at an example to understand the above two scenarios. Let's consider our PersonService class and PersonRepository class. We would be writing unit tests for the `delete()` method of PersonService class. The `delete()` method of PersonService class is dependent on `delete()` method of PersonRepository class, which has return t

How to verify method arguments using Mockito

 How to verify value of an argument passed to a mocked method? While writing unit tests, we might need to verify the parameters passed to a dependency method, from the method being tested. Mockito provides an easy way to achieve this.  Mockito provides ArgumentMatcher class that can be used to verify arguments passed to a mocked method. We will be using the UserService and UserRepository class in this example. UserService is the class that is being unit tested and UserRepository is a dependency class that has to be mocked. UserService @Service public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository = userRepository; } /** * Save a user in database * * @param id * @return */ public Optional<User> findById(Long id) { if (id == null) { throw new RuntimeException("Id is required"); } ret

How to specify return value from a method using Mockito

Mockito allows you to specify what to return when a method is called on a mocked object. Mockito supports two ways to do it: `when-thenReturn` and `doReturn-when`. In most cases, `when-thenReturn` is used and has better readability. Below is the example usage for testing our UserService class that has dependency on UserRepository class. UserServiceReturnOptionsTest /** * Test class to show example implementation of when-thenReturn and doReturn-when pattern of Mockito to define return * types from a mocked method. */ class UserServiceReturnOptionsTest { /** * This method used when-thenReturn pattern to set return value from a mock object */ @Test void when_then_example() { // Create a mock object for dependency class UserRepository mockUserRepository = Mockito.mock(UserRepository.class); // Add mocked dependency to the class object being tested UserService userService = new UserService(mockUserRepository); /

How to verify that a method is called using Mockito

As part of writing unit tests, many times we might need to verify that the tested method is calling an external dependency method. Let's consider the following UserServer and UserRepository classes. UserService class is dependent on UserRepository class for fetching a User object with given Id. While writing a unit test for findById() method, it makes sense to verify that findById() method of UserRepository is actually invokes. UserService @Service public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository = userRepository; } /** * Save a user in database * * @param id * @return */ public Optional<User> findById(Long id) { if (id == null) { throw new RuntimeException("Id is required"); } return userRepository.findById(id); } } UserRepository public interface UserReposit

How to mock a dependency using Mockito in JUnit

 How to mock and inject dummy implementation using Mockito for Unit Testing? In this article we will explore the various ways of defining a mock implementation for a dependency class in Unit Tests. For writing Unit Tests, we have to decouple the tested class from any of its dependencies. Mockito provides us an easy way to define mock implementation and control response from a dependency class/method. Let's use the UserService.java and UserRepository.java classes from our previous article on  Mocking external dependencies in Unit Tests using Mockito framework . UserService.java package com.devnips.mockitojunit5.service; import com.devnips.mockitojunit5.model.User; import com.devnips.mockitojunit5.repository.UserRepository; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository

Mocking external dependencies in Unit Tests using Mockito framework

 In the previous article we saw how we can decouple classes for Unit Testing by creating dummy classes . In this article we will rewrite the same example using Mockito framework. Mockito makes it super easy to write dummy classes in a declarative way. Let's take the same example of UserService and UserRepository classes. We are going to write a Unit Test for fineById() method of UserService class. We will mock and inject UserRepository as a dependency to UserService class. UserService.java package com.devnips.mockitojunit5.service; import com.devnips.mockitojunit5.model.User; import com.devnips.mockitojunit5.repository.UserRepository; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository = userRepository; } /** * Save a user in database * * @param id * @retu

Mocking dependencies without using Mockito Framework

In this post, we will learn how we can create dummy implementation of a dependency class and use it in our Unit Test. Let's consider following UserService class. UserService.java package com.devnips.mockitojunit5.service; import com.devnips.mockitojunit5.model.User; import com.devnips.mockitojunit5.repository.UserRepository; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository = userRepository; } /** * Save a user in database * * @param id * @return */ public Optional findById(Long id) { if (id == null) { throw new RuntimeException("Id is required"); } return userRepository.findById(id); } } This class is a Spring bean and has dependency on UserRepository interface. UserRepository interface is

A very simple JUnit5 test

 A very simple JUnit test would be a case where we are testing a method or a class that has no dependency on any other class. For example below is a simple calculator class that calculates sum of two numbers. To write a unit test for this method, we simply call the add method and verify the response. This test does not require any use of Mockito framework and can be created by using just the JUnit framework.

How to pass list of parameters using Spring Feign

We can use Spring Feign to connect to external APIs. Feign makes is very easy to connect to external APIs by providing a declarative approach and encapsulating lots of connection logic. In this article we will discuss about how we can pass a list of values as a URL Query parameter to an api. A webservice URL can accept a list as a parameter in one of the below two formats. 1. Repeated parameter name /search/findByIdIn?ids=1&ids=2&ids=3 2. Comma Separated Values /search/findByIdIn?ids=1,2,3   In general case, an API coded in one of the above formats can not accept parameters in the other format. As a consumer of these APIs we can not control the format used by the API. Feign provides simple solutions to choose between these types. 1. Repeated parameter name To pass a list as repeated Query parameters, simply define the Feign methods to accept parameter as a List object.  Example 2. Comma Separated Values To pass a list as comma separated values in URL query parameter,