How to write junit test cases for spring rest controller

seems excellent phrase What words..

How to write junit test cases for spring rest controller

Are you tired of writing tests which have a lot of boilerplate code? The first part of this tutorial described how we can configure our unit tests which use the Spring MVC Test framework. Well, a normal controller in the context of this blog post is a controller which either renders a view or handles form submissions. We can get the required testing dependencies by adding the following dependency declarations to the POM file of our example application:.

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:.

how to write junit test cases for spring rest controller

Every unit test which we write to test the behavior of a controller method consists of these steps:. These classes are described in the following:. Next we will take a look at some examples which demonstrates how we can use these classes in our unit tests.

We will write unit tests for the following controller methods:. The implementation of the controller method which is used to show the information of all todo entries has the following steps:. Before we can write the actual unit tests for our controller method, we have to take a closer look at the implementation of that method. The controller method which is used to show the information of a single todo entry is implemented by following these steps:. In the previous part of this tutorial, we created an exception resolver bean which is used to handle exceptions thrown by our controller classes.

The configuration of this bean looks as follows:. First, we must ensure that our application is working property when the requested todo entry is not found. We can write the test which ensures this by following these steps:. Second, we must write a test which ensures that our controller is working properly when a todo entry is found.

We can do this by following these steps:. Again, we will first take a look at the expected behavior of our controller method before we will write the unit tests for it. The controller method which handles the form submissions of the add todo entry form is implemented by following these steps:.

As we can see, the controller method uses a TodoDTO object as a form object. The TodoDTO class declares some validation constraints which are described in following:. If we think about the tests which we should write for this controller method, it is clear that we must ensure that.

how to write junit test cases for spring rest controller

First, we have to write a test which ensures that our controller method is working properly when the validation fails. We can write this test by following these steps:. This method creates a new String object with the given length and returns the created object. The source code of the TestUtil class looks as follows:. Second, we have to write a test which ensures that our controller is working properly when a new todo entry is added to the database. This tutorial has taught has four things:.

You can get the example application of this blog post from Github.We will use two difference approaches to write unit tests. Following screenshot shows the structure of the project we will create. We typically work in large projects - some of these projects have more than source files or sometimes it might be as big as files with one million lines of code.

Before unit testing, we depend on deploying the entire app and checking if the screens look great. And it is manual. JUnit is a framework which will help you call a method and check or assert whether the output is as expected. The important thing about automation testing is that these tests can be run with continuous integration - as soon as some code changes.

When we write a unit test for SomeBusinessImpl, we will want to use a mock DataService - one which does not connect to a database. The important dependency for unit testing is spring-boot-starter-test.

Lets create a simple DataService. Actually this should talk to some database to get all the data but for now lets keep it simple and return hardcode value.

This will be a dependency for the BusinessService. Example code below shows how we can write the same unit test launching up the complete Spring context. Launching the entire spring context makes the unit test slower. Unit tests will also start failing if there are errors in other beans in the contexts. So, the MockitoJUnitRunner approach is preferred. 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. We will also start looking at a basic implementation of a microservice with Spring Boot. In part 1 of this series, lets get introduced to the concept of microservices and understand how to create great microservices with Spring Boot and Spring Cloud. At in28Minutes, we have created more than 20 projects with code examples on Github. These code examples will you learn and gain expertise at Spring Boot. What are the best practices?

Here's a list of video tutorials and courses for you. After ; import org. AfterClass ; import org. Before ; import org. BeforeClass ; import org. Test; import org. RunWith; import org. InjectMocks; import org.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.

how to write junit test cases for spring rest controller

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.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.

Spring boot JUnit example with RestTemplate

The second method does the same, but because it is for findAllById, it is checking just one object equality.Adding a suite of tests builds confidence that your application can handle anything thrown at it. When building your tests, it is important to use a modern and comprehensive suite of tools. Using a modern framework ensures that you can keep up with the changes within your language and libraries. A comprehensive suite of tools ensures that you can adequately test all areas of your application without the burden of writing your own test utilities.

JUnit 5 handles both requirements well. There are three POST endpoints you will be able to use to determine either the day of the week, the astrological sign, or the Chinese Zodiac sign for a passed in birthday.

Text code marketing

The main advantage of using the Spring Framework is the ability to inject your dependencies, which makes it much easier to swap out implementations for various purposes, but not least of all for unit testing. Spring Boot makes it even easier by allowing you to do much of the dependency injection with annotations instead of having to bother with a complicated applicationContext.

If you are using Eclipse as well, you will need to install a version of Oxygen or beyond in order to have JUnit 5 Jupiter test support included. For this tutorial, the structure of the project is as shown below. I will only discuss the file names, but you can find their path using the below structure, looking through the full source, or paying attention to the package. If you use a different IDE, there are likely equivalent steps. Optionally, you can create your own project directory structure and write the final pom.

Select the location of your new project and click next twice and then fill out the group id, artifact id, and version for your application. For this example, I used the following options:.

When done, this will produce a pom. Take note that you need to exclude the default JUnit from the spring-boot-starter-test dependency. The junit-jupiter-engine dependency is for JUnit 5. The SpringBootApplication annotation tells the application that it should support auto-configuration, component scanning of com.

It is pretty straight forward, defining that there are four helper functions available. It looks like this:. First, you will notice the following annotations near the top. You could also use the Controller annotation, but it means that you would have to add more boilerplate code to convert the responses to an HTTP OK response instead of simply returning the values.

Guide to Testing Controllers in Spring Boot

I will show a full path for an endpoint later. Next, you will see a class variable for birthdayService of type BirthdayService.Previously we saw how to create a spring mvc restful web service.

Unit testing is a software testing method to test individual units of source code. JUnit is by far the most popular unit test framework. We start by showing how to configure Mockito, to mock the responses returned from the service, and inject the mocks into the rest service controller. You can download the full working example on the bottom of the page, this includes the entire rest service together with all the services and unit tests.

Some important classes explained:. By annotating the UserService with the Mock annotation, we can return mocked data when we call a method from this service.

Santander bank statement template

Using the InjectMocks annotation, we can inject the mocked service inside our UserController. Before each test, we must initialize these mocks using the MockitoAnnotations initMocks this. Optionally we can add filters, interceptors or etc. Now that we have configured Mockito with Spring Test Framework, we can start writing our unit tests for our spring mvc rest service. Here is an overview of each HTTP method:. Here is an overview of the full working example. You can download the entire project at the bottom of the page.

May 11, November 9, April 24, Nice article. The code is working as expected as well. Is there any additional configuration needed to run the integration tests? UserControllerIntegrationTest Time elapsed: 0. HttpClientErrorException: Forbidden. A nice tutorial, but I have a question, in my User class, I have a dateOfBirth field with reference type is LocalDate from joda-timewhat is the correct syntax for testing that field? Hi, Thank you for the post and information.

Have an issue. Trying to run unit tests with your reccomendations, but getting such error. After you create the ResourceType instances, you have to insert them into the list you created.

Anyway, I cannot see your entire source-code.

Perko distributors

Do you have some kind of initialization going on in your constructor? I gan definitely see a NullPointerException occurring there. Hi, Thank you for this tutorial. Discover more articles. Download it — unit-test-spring-mvc-rest-service-mockito-junit-example.By using our site, you acknowledge that you have read and understand our Cookie PolicyPrivacy Policyand our Terms of Service. The dark mode beta is finally here. Change your preferences any time. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

I have a controller which responds to REST calls, I have various test cases for my other public methods. Take a look at MockMvc. It's part of Spring Test module. These tutorials are pretty descriptive and going into details so you should get idea straight away how to test Spring MVC controllers.

Sample code for this post is available on Github. Learn more. Spring Junit test case for controller rest service Ask Question.

Unit Testing of Spring MVC Controllers: REST API

Asked 5 years, 6 months ago. Active 2 years, 10 months ago. Viewed 14k times. Kousick Shanmugam Nagaraj Kousick Shanmugam Nagaraj 2 2 gold badges 7 7 silver badges 19 19 bronze badges. To be honest, I don't think unit testing this method is of much worth.

The only thing you can really check is that it correctly forwards the parameters to getFrames function and then converts each FrameVariant to a Frame. Both that function and the conversion constructor should unit tested any way. This functionality should be tested as end to end testing, ie deploy this service and a 'test data set' and make an actual HTTP requests. Active Oldest Votes. Do you have some objections why it wouldn't? From my point of view, team has to decide what is most effective testing for them.

Sign up or log in Sign up using Google. Sign up using Facebook. Sign up using Email and Password. Post as a guest Name. Email Required, but never shown. The Overflow Blog. Featured on Meta. Community and Moderator guidelines for escalating issues via new response…. Feedback on Q2 Community Roadmap. Technical site integration observational experiment live on Stack Overflow. Dark Mode Beta - help us root out low-contrast and un-converted bits. Linked Related Hot Network Questions.

Question feed. Stack Overflow works best with JavaScript enabled.


thoughts on “How to write junit test cases for spring rest controller

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top