Junit rest api testing using mockito spring boot
Are you tired of writing tests which have a lot of boilerplate code? However, writing comprehensive and fast unit tests for these APIs has been troublesome. The release of the Spring MVC Test framework gave us the possibility to write unit tests which are readable, comprehensive and fast.
During this blog post we will write unit tests for controller methods which provide CRUD functions for todo entries. If you wan to get up-to-date information about writing unit tests for Spring and Spring Boot web apps, you should take a look at my Test With Spring course:. We can get the required testing dependencies by adding the following dependency declarations to our POM file:.
The unit tests which we will write during this blog post use the web application context based configuration. This means that we configure the Spring MVC infrastructure by using either an application context configuration class or a XML configuration file. Because the first part of this tutorial described the principles which we should follow when we are configuring the application context of our application, this issue is not discussed in this blog post. The application context configuration class or file which configures the web layer of our example application does not create an exception resolver bean.
The SimpleMappingExceptionResolver class used in the earlier parts of this tutorial maps exception class name to the view which is rendered when the configured exception is thrown. This behavior is provided by the ResponseStatusExceptionResolver class which is enabled by default. Our example application also has a custom exception handler class which is annotated with the ControllerAdvice annotation.
This class handles validation errors and application specific exceptions. We will talk more about this class later in this blog post. Next we will see the Spring MVC Test framework in action and write unit tests for the following controller methods:. The first controller method returns a list of todo entries which are found from the database. The controller method which returns all todo entries stored to the database is implemented by following these steps:.
The returned JSON document looks as follows:. The second controller method which we have to test returns the information of a single todo entry. The controller method which returns the information of a single todo entry is implemented by following these steps:. Our example application has an exception handler class which handles application specific exceptions thrown by our controller classes. This class has an exception handler method which is called when a TodoNotFoundException is thrown.
The implementation of this method writes a new log message to the log file and ensures that the HTTP status code is send back to the client. First, we must ensure that our application is working properly when a todo entry is not found.
We can write an unit test which ensures this by following these steps:. Second, we must write a test which ensures that the correct data is returned when the requested todo entry is found. We can write a test which ensures this by following these steps:. The third controller method adds a new todo entry to the database and returns the information of the added todo entry.
The controller method which adds new todo entries to the database is implemented by following these steps:. As we can see, this class declares three validation constraints which are described in the following:.
Because I have already written a blog post which describes how we can add validation to a REST API, the implementation of the error handler component is not discussed in this blog post.
However, we need to know what kind of a JSON document is returned to the client if the validation fails.People who are familiar with Mockito, we use Autowired directly to call the methods from our junits. Same way, if you are using Mockito then we need use InjectMocks for our actual service class where we are trying to write the test cases for the classpath.
Now you can run testCoupons method to test the getCoupons method of couponServiceImpl. Same way you can write n number of methods as per your need for all your possible test cases for both positive and negative. Your email address will not be published. Notify me of follow-up comments by email. Notify me of new posts by email.
This site uses Akismet to reduce spam. Learn how your comment data is processed. April 9, Frameworks. Table of Contents. Share this: Click to share on Facebook Opens in new window Click to share on Twitter Opens in new window Click to email this to a friend Opens in new window Click to print Opens in new window. Leave a comment. Leave a Reply Cancel reply Your email address will not be published.
Sorry, your blog cannot share posts by email.Learn to write unit tests for service layer of Spring application using JUnit and Mockito testing frameworks. This tutorial demonstrate spring boot test service layer example. The spring-boot-starter-test dependency includes all required dependencies to create and execute tests.
In this example, we are unit testing primarily two classes EmployeeManager and EmployeeDao. As name implies, manager class represents service layer and dao class is interacting with database.
EmployeeManager class has a dependency on EmployeeDao and delegate method calls to get the data which pis finally returned to controller classes. This method also, upon initialization of junit tests, initializes the mock objects. In above example, we have annotated EmployeeManager class with InjectMocksso mockito will create the mock object for EmployeeManager class and inject the mock dependency of EmployeeDao into it.
Few example methods could be getAllEmployees which will return list of EmployeeVO objects, getEmployeeById int id to return a employee by given id; and createEmployee which will add an employee object and return void. In this mockito tutorialwe learned to unit test the service layer in spring boot applications using JUnit and Mockito.
We learned to setup the test class and writing JUnit tests. A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.Comment 0. Spring Boot is an open-source framework for application creation, and where we create our APIs. I prefer the following combination: Spring BootJUnitMockMvcand Mockitobecause they are all open-source and support Java, which is my preferred language.
These are my personal preferences but EclipseNetBeansor even a simple text editor could also be used.
You can also participate - the source code is located here. We will be testing controllers and repository classes. We will write tests per controller testing the size of the JSON Object, the status of the call to the endpoint and an assertion on one item from the JSON object and tests per repository inserting two new items in a table and making sure the return object is equal.
Make sure you have JDK installed at least version 1. If you did everything correctly, you should now see this window with an empty Java project:. Now that we have a project, we need to setup the dependencies. You can use these dependencies since they are public.
To do that, double click on your build. The file will be created in the default place. You can see this in the following screenshot:. For that reason, I create the test classes by myself. The reason we have two is that we have two methods in the controller itself, so we want to test them both. The second test method does the same for the getArrivalsById.
Now we can execute this single test by clicking the play button at the beginning of the line of the method name see the following picture. The purpose of this execution is to make sure the test is working properly:. After execution, you will see the results of test execution, including the status, count, and stacktrace. We can see that our test passed on the left sidethe number of tests the progress bar is in the middle up top and the stacktrace for execution.
The next step will be to add tests for all controllers. This is a unit test that is covering the database testing part.
For example, writing test data to the DB and afterward verifying it is properly stored. In this test, we are using the H2 database for testing. This is common practice. This is not necessary when you use the H2 DB because it is in the memory. After the test s is finished, the database will be fully dropped. The second method does the same, but because it is for findAllById, it is checking just one object equality.Please note: The following article will be dedicated to testing Spring Boot applications.
There is a general lack of testing in most organizations. Maybe even your team is one of those teams that have good intentions on testing, but it always gets put off or forgotten as the projects get rolling.
Why is testing so hard to do consistently? Testing benefits are well-known, and yet, why is it so often overlooked?
First, creating, integrating and maintaining tests can often be difficult. And second, unless you're an engineer that has done a lot of testing, and seen its importance and value, you probably won't place it high on your priority list to learn and make a part of your development process.
Fortunately, Spring Boot is making integrating and working with tests easier than ever before. When it comes to testing there are several different types of tests that you can write to help test and automate the health of your application. However, before we can start doing any testing we need to integrate the testing frameworks. With Spring Boot, that means we need to add a starter to our project dependencies, for testing we only need to add the spring-boot-starter-test dependency:. The first framework that test starter will integrate is JUnit.
JUnit has been around for a long time, and if you've ever unit tested in Java, you've most likely used this framework before. When doing basic unit testing, JUnit and Spring complement each other well, as you'll see in some upcoming demos. Even though JUnit provides some assertion support to help analyze test results, Spring Boot also incorporates Hamcrest. This framework provides improved test results matching and assertions, that when combined with JUnit allow you to automate your testing from start to finish.
The next framework that test starter integrates is Mockito.
Unit Test Spring MVC Rest Service: MockMVC, JUnit, Mockito
Sometimes, when testing, the code you're trying to test is a dependency for another object. Sometimes, it's simply a piece of code that's hard to prop up for a unit test.
In such cases, using a framework like Mockito to mock and stub those objects is the solution. This way, you can proceed with your tests and then verify what was called and used on that object after your test is run.
These include annotations, test utilities, and other testing integration support that allow working with JUnit, Hamcrest, and Mockito within the Spring environment.This guide will help you write great unit tests for your Spring Boot Rest Service. We will use a simple code example creating couple of simple rest services. Following screenshot shows eclipse project with all the files we will create.
We want to create a unit test for StudentController which is a Rest Controller. StudentController exposes two service methods - one Get and one Post. We will write unit tests for both these service methods. A key part of unit testing is to restrict the scope to a minimum. In this unit test, we want to test only the methods in StudentController. All applications need data. Instead of talking to a real database, we will use an ArrayList - kind of an in-memory data store.
A student can take multiple courses. A course has an id, name, description and a list of steps you need to complete to finish the course. We have StudentService exposing methods to. Refer to these files at the bottom of the article for exact implementation of the Service StudentService and the model classes Course and Student. The Rest Service StudentController exposes couple of get services.
Response is as shown below. Below picture shows how we can execute this Get Service from Postman - my favorite tool to run rest services. When we are unit testing a rest service, we would want to launch only the specific controller and the related MVC Components. This can be used when a test focuses only Spring MVC components. Using this annotation will disable full auto-configuration and only apply configuration relevant to MVC tests. Also return the location of created resource as a Response Header.
Below picture shows how we can execute this Post Service from Postman - my favorite tool to run rest services. Make sure you go to the Body tab and select raw. Select JSON from the dropdown. Copy above request into body. In the response, we check for HttpStatus of Created and that the location header contains the url of the created resource.
Do not know where to start your learning journey? Why Is Docker Popular? What is DevOps? How is it different from Agile? What are the popular DevOps Tools? Let's get started with a simple usecase. In this article, we focus our attention on the cloud. In this article, we explore an important non functional requirement called performance.
This resources will help you learn and gain expertise at Spring Boot. Let's learn the basics of microservices and microservices architectures.GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.
Some menu here
If nothing happens, download GitHub Desktop and try again. If nothing happens, download Xcode and try again. If nothing happens, download the GitHub extension for Visual Studio and try again. It has awesome unit testing capabilities through Spring Boot Starter Test. Mockito is the most popular mocking framework. You will learn to write independent unit tests for RESTful web services talking with multiple layers - web, business and data.
You will learn how to write integration tests using an in memory database H2. You will build the unit tests step by step - in more than 50 steps. This course would be a perfect first step as an introduction to unit testing with Spring Boot and Mockito Frameworks.
Spring Boot: Unit Testing and Mocking With Mockito and JUnit
We will help you set up each one of these. Skip to content. Dismiss Join GitHub today GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together. Sign up. Java Branch: master. Find file. Sign in Sign up. Go back. Launching Xcode If nothing happens, download Xcode and try again.
Latest commit. Latest commit cef Dec 9, Assert org. BDDMockito org. Mockito org. Assertions org. Matchers org. CoreMatchers org. Requirements You should have working knowledge of Java and Annotations.
We will help you install Eclipse and get up and running with Maven and Tomcat.