Skip to main content

Posts

Showing posts from 2021

Null Check In Java

Java has evolved over the years. Below are few of the methods to check whether an object is Null or not in Java. Java 5 Before Java 8 we were able to check for an object being Null by using a simple `if` statement, as shown in code below: public void preJava8(String s) { if (s == null) { // do something System.out.println("String is null"); } System.out.println("String is not null"); } Java 8 With introduction of `Optional` class in Java 8, we can use it to perform actions on an object if its value is not null. public void java8Optional(String s) { Optional.ofNullable(s) .ifPresent((str) -> { //do something System.out.println("String is not null"); }); } Java 9 Java 9 enhances the Optional class to provide an els

Junit5 Parametrized Tests

 What are parameterized unit tests and How to write them using Junit5? In this article we will learn about parameterized tests and how to write Junit parameterized tests. The parameterized tests is the concept of running a single test multiple times, but with different parameters and outcomes. The parameterized unit tests allow us to avoid writing same code multiple times. JUnit 5, the newest version of JUnit, adds a slew of new capabilities to make creating developer tests easier. Parameterized tests are one such feature. This feature allows us to repeat a test procedure with varied parameters many times. To start writing parameterized tests, we first need to include `junit-jupiter-params` dependency in our project. For Maven, add below dependency to the project's pom.xml file. <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-params</artifactId> <version>5.7.0</version> <scope>test&l

Test Callback Invocation using Junit5 and Mockito

In this article we will use thenAnswer method of Mockito to invoke a callback method passed to a mock.  Let's consider following classes. Here, ServiceToBeTested class is calling submitCallback() method of ServiceToBeMocked class and passing it a Callback object. The value set in Callback object is latter returned by the method being tested. ServiceToBeTested.java public class ServiceToBeTested { private final ServiceToBeMocked serviceToBeMocked; public ServiceToBeTested(ServiceToBeMocked serviceToBeMocked) { this.serviceToBeMocked = serviceToBeMocked; } public String methodToBeTested() { Callback callback = new Callback(); serviceToBeMocked.submitCallback(callback); return "Value Received after callback = " + callback.getValue(); } } ServiceToBeMocked.java public class ServiceToBeMocked { public void submitCallback(Callback callback) { //some logic that sets value back in callback.

How to verify values passed to a mocked method?

 In this tutorial we will learn how we can verify values passed to a method. Many times we want to verify values passed to a method while execution of the method being tested. This situation may arise when invoked method has no effect on the calling method. Eg. Publishing an event. Let's take a look at the following example, where the `updateBalance()` method is calling `NotificationService` method to publish an event. AccountService.java public class AccountService { private final NotificationService notificationService; public void updateBalance(String accountNumber, BigDecimal newBalance) { // some calculations notificationService.publish(new AccountUpdatedEvent(accountNumber, newBalance)); } } NotificationService.java public class NotificationService { /** * Publish an event to the message broker * * @param event */ public void publish(Event event) { // logic here to write to message broker } } Now

Setup Lombok with Spring Boot

 Lombok is a Java library that takes care of generating lot of this boiler plate code for the developers. Lombok works by plugging into your build process and hooking into Java byte-code generation stage, to add required code based on your specifications. Lombok uses annotations to identify which piece of code needs to be auto generated. Adding Lombok to any project is very simple. You simply have to include the  Lombok package in your build path.  If you are using Spring boot, Lombok version will be resolved for you by Spring. Maven pom.xml <parent> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-parent</artifactid> <version>2.3.12.RELEASE</version> <relativepath> </relativepath></parent> <dependencies> <!--https://mvnrepository.com/artifact/org.projectlombok/lombok--> <dependency> <groupid>org.pro

Adding Custom Validation in Lombok Builder

What is Lombok? Lombok is a Java library that auto generates lots of boiler plate code for Java classes. Lombok works at compile time and manipulates Java byte code to add additional features. Lombok uses annotations to specify what boiler plate code will be generates. Eg. @Getter annotation can be applied to any Java bean to auto generate Getter methods for all the fields in that bean. In this article we will be looking at, how to add custom validations on fields using Lombok Builder annotation What is Builder annotation in Lombok? Lombok can be used to generate Builder class for a Java bean, by annotating the bean class with @Builder annotation.  In certain cases, we might want to validate the data, in builder class, before creating the bean object. Lombok provides simple validator annotations like @NonNull to enforce nullability checks. But what if, we want to have more custom validations or want to throw custom errors. Customizing Lombok Builder class. Let's consider below Emp

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,