Test Rest API's using WebMvcTest and MockMvc annotations | Testing in spring boot

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello friends welcome in this video tutorial we are going to look at how to test REST API using Raman recetas and mock and VC so before we get started let's first discuss what exactly value is a test is so param sita's is an application that focus only on spinning recetas which means it is used to test the controller layer of your application since it only deals with a controller layer of your application it will not load the full auto configuration it will just load the configuration related to and we see test that is your controller layer the important thing to remember here is that using memory centers we are testing the implication between the controller and HTTP layer of application but not the integration between a controller layer and the business logic of your application so since it only bootstrap the simple controller will be using mock mini notation to mock away the business logic and to create the dependency you needed by our controller we will be using more convincing annotation along with backseat as a notation which will move the HTTP request and HTTP response without needing to start the real server so to demonstrate how to use the babysitter notation we will create a very simple user application which will be consists of two rest api using Springwood app so we will first start by creating a REST API which will be of type get localhost colon 8080 slash user slash user ID which will return the user details and then we will go ahead and create another REST API which will be of type post localhost colon 8080 slash user which will save the user details in the application and we will build both this REST API from scratch and then we will test it out using babysitter's and ma communication so let's get started okay so let's clear our springboard are using spin initializer so let's go to start our springboard I all okay so for the group ID we will in turn they have talked us for the artifact ID we will enter first API test okay now we will add the dependencies for this user demo so we're gonna require the spring web as well as spring data JPA and for this demo application we will be using s2 database okay so all the differences have been defined and added now let's go ahead and click on the generate button to generate this they were up okay a zip file has been downloaded let's copy this zip file and I will paste this and my H Drive de modest project folder okay next we will extract this and we will extract this under demo test project folder okay so the default I've been expert there and we can now see the contents of this this spring good app okay so now let's open this spring trap and the IDE new file open okay let's open this in a new window so her replication is successfully imported let's first have a look at the pondered XML file so at the time of this video record in this ping good wasn't it we are using is 2.20 dot release and if you scroll down a little they also include spring will start at s dependency and if you click on the momentum on the right hand side here and inspect the spring boosted at s dependency you will find that it includes J when it was at five and it also includes other transitive dependency we should be required for the testing so now let's go ahead and configure average to database which we will be using for our user demo application so let's maybe get to application properties file which is under resource folder and for our extra data source we will have these following properties the name of the database will be test TV we driver class name is Aldo destroy driver user name is si password will be blank and we have kept the hibernate or DD elders auto property equal to update so that at the equation strata our tables will be created with respectable entities if you are following me you can just pause the video and type out this properties menu okay so now let's go ahead and create our first rest API which will return the user details based on a given ID we will follow a test-driven development approach and we will create a tests class first and then we will go ahead and drag the remaining code from there so under the test folder and piggys come to our tape to'kustar to rest api test create a class called user controller test okay now the first thing we need to do is annotate this class with program and received as a notation and then this annotation we will provide the name of the controller class which we are going to test and the name of our controller class will be in user controller class okay so this user code or glass is still does not exist so let's go ahead and create this user controller class and we will create this user controller class and I'll call dr. Tucker's dot REST API it is dot controllers and will annotate this controller class with less controller ice we are able to expose our services okay so now let's get back to our user controller test class and provide the user controller class okay also what about the more can we see which we will be using for blocking the HTTP request and response okay so from a per user controller we will be using a service layer which will return the user a 10-person a give an ID so we will be mocking that service layer so let's use the notation mocking on our service layer and we will call the service layer as user service okay and now let's go ahead and create this is a service interface and we will name this interfaces we will get it under service and we will name this simple research user interface oh we don't have to provide the name here we just have to provide the package name click on the ok button and the sacrifice has been created and this interface will have matter which will return the user and we will name this matter as get user ID and this function will accept Trudeau maker ID which is of type int ISA okay so now this model requires the user into the object to be returned so now let's go ahead and create this user class and we will create this in the class under entity package okay since this is a valid shipping in Turkey people annotated with entity and this is a class will have an ID field which will be of type which will be a priming key and we do annotated abate take it Invicta strategy to the entity and this is the class will have other fields as well like the username email okay let's go ahead and clean the getters and setters for these spheres okay so now I will use our data classes ready now we will get back to a user interface and there is gone so let's create the implementation class of this user service so under the service package we will create another class and it will name this class as user service I am Pierre we will annotate this class service on occasion and then this flash sorry reminding our users of this interface and we now we will over direct e gives our value method which we have defining the user interface service interface okay and this is a service layer will talk to the repository layer to KT user details so let's auto buyer user repository here [Music] safely inside the project Li and we'll go ahead and create this class and we will play this class and the project repackage and this crew this will be an interface and this will extend and this will extend the JPA by project Li okay so let's get back to you the second time here and Rob this matter get user ID we will set the return usually possibly dot find by ID and it will pass the ID and dot get so this will now return the user details completely it was it to layer okay so let's scale back to our user controller first and write our test method so let's start took this method and we will say a public void get user pride Heidi test we will be testing the rest API which will return the user it is based on a given ID so let's first write down the step-by-step process which we need to perform in order to test in REST API so the first thing that you need to do is we have to Bob the data that will be returned by the user service method get user by ID and then we have to create a mock HTTP request to verify the expected response from the REST API so let's write down the steps so first thing that you need to do is we have to move the data we can wire up we use a service for us and then we need to perform a mock wait a mark HTTP request to very quietly expected result okay so our user service will return the user details based on the given ID so we need to set up the user object for our mock data so let's say user user equal to new set the name of the user to John set the email to John until 8:30 calm I shown phone number to any random number and it's on Xandar okay he's a god set okay so all the properties I can say we're going to set an another property and so now how does how to move the data when they use a service get user by ID method is called so to mark it what we need to do is when use a service method get user by method is called we should return the mob choose a data service dot get user variety which will accept any teaser and they salute on the mark in the data okay so our first step is done now let's go ahead and create the more cast utility torso mo can we see your form locking the seal press builders doll gate and our API will be user slash any user ID and we are extracting status code to be 200 along with the status code we also need to verify that the response would invite this API should match with the multi user data so let's do that we will say dot and expect we will use the class mode every see result measures to match the response data the property name and this should equal to John and similarly we will for other fields as well email phone and gender add this email ship to be John at their depth e.com this four should have value nine six five eight five zero two six two and the gender should have a haven so in order to test this we first have to create this West API which we have not created yet so let's go ahead and click this rest and put and then we will test this out okay so let's jump to use a controller and create the get request API and the qrow should be user slash ID and this will return response entity with user data and we will call this method get user by IT here we will expect the class variable ID private teaser and here time the response entity and all the other service dot K to use a piety method and here we will pass the path very politely and we'll dish should return as too difficult two hundred on successful education okay so we have not autovalue the surface let's do that Jesus always use a service so a strength point is ready and let's go ahead and test this out let's jump to user controller tab and we will run this and verify that this rest endpoint uses less with the ID of 12 there's one this so we have successfully tested this rs10 point and as you can see the test cases are all passed okay so let's do one more thing here I will add another one here crane okay so what this chain method will do here it will it will print the requests and response on the console which may be helpful for debugging so let's run this test again and see and verify that the the data that we have marked is successfully written by this API or not let's see that okay so we will be able to see the request and response here as you can see so we have made a get request on a URI user with ID of 12 and and the response that we have got is this status code 200 contained diversification /i shown and as you can see the data that we have not and that test is successfully verified and it is also returned as the response body when this HTTP mock request is performed here the one thing that I want to tell you guys is that if using J even if all you need to add one more annotation along with the visitors and the annotation is row with a notation and you have to pass the spring on a door class okay so the first task of creating get request which returns the user details has been done now let's go ahead and create another API which is of typos that will save the user details so let's start by adding the test first public void and we will call this method name it save you the test okay and let's start down the steps that we need to perform here the first thing that we have to do is we have to move the user data that we want to save okay and then we have to create a mock request mug request this mock request URL will be slash user and this will save the mob to user data it will mock like that it is saving the user details okay so let's start with the first step that is to mock the user data so I will just copied the amount user data that we have done in the gate user body test method so I will just copy this and paste it here I will read one more set up here for the ID field and let's say for now it it is one we are saving a user with an ID of one with the name John and with email John is it a dev t.com with four nine six five five zero two six two and gender as well and now we have to know the behavior and we call the save user api's then our user controller will call the user service and the end user service will save the user details so we have to remove the behavior when the user services trying to save the user so we will say when use a service start save user with any user class with any user object then we want to return the malt user data from the service layer so we have to create this save user method which we have not created yet so let's create this method and this will return the saved user ok what is and let's go ahead and implement this matter inside the user service I'm here overwrite the matter save user and here called user repository dot save and we'll pass the user object let's get back to our controller classic in that is gone and now we perform the mod also request to save the user details so let's say mark and we see got a form what can we see what can we see request builders and we will do a post here and a post URL will be slash user and the content type would be just on and what we expect is we expect this expect the status poopy is created so we will send the HTTP code as two zero one whenever this user is created by this API and and we expect that whenever this user is created we expected the ID field to be present in the response body so here we say what can we see his ultimate dot JSON path and we want to verify that the ID field is exist in the response body whenever the user is created similarly we will asserts the other properties here so I will just copy the fields from our previous method and just paste it here we also need to pass this user object in the request body of this post API so let's do that so it'll pass this user object and we need to pass the user obligates a JSON string for that it will use object mapper class which will write this user object as a JSON string okay so my second step is done now let's go ahead and create this post API which is not created here so let's jump to user controller class and clear the post API and the endpoint for this API will be user this will also return the user object as a response I will name this matter as save user and this will let's expect this class body I will use it and here we will call the user service layer and we call this either matter on your service class class the first body and then we will return the city B status chorus to zero one okay so now our API is for post request has been created let's get back to user control class and read this test and verify the result of our post API okay so test is running now okay so what this case is passed and we have successfully created a post API slash user receive the user editors let's do one thing let's intentionally fill this test case by changing the name here and I will change the name to anything I will say memory and let's run this again and they should fail now okay so this case is filled as expected as we intentionally did it so here it says that the expected name will you is married but the actual where it was is on because and the Mounties are object we said there's an Amazon but here we are verifying that the username should be married so that's why this test case is failed so this verifies that this is working as expected I will just change this back to John okay so both of our task of creating the gate API to retrieve the user details as well as to save the user has been done so in this video guide we have seen that how to use the remm see test or no test to test the attraction between the controller layer and the HTTP layer of our application and you guys may be wondering that why we have created this user repository and also use this user repository from our user service idea class but we have not used it in any half of a test method and this is because we are testing the interaction between the controller layer and the HTTP layer of our application we are not concerned about the business logic here so using the permutation notation we have created a mark server which sends a mock SATP request and mark SATP response so in the next video i will show you how to do an end-to-end integration testing in which we will start a real server on a random port and we will test all those of our application from controller to service and from service to repository so test it for now I will see you in the next video thanks for watching
Info
Channel: DevTalkers
Views: 11,648
Rating: undefined out of 5
Keywords: spring boot, mockmvc, webmvctest, rest api, unit testing, testing, junit, tdd, test driven development, testing in spring boot, devtalkers, spring boot testing
Id: qPDheVUyH9k
Channel Id: undefined
Length: 36min 37sec (2197 seconds)
Published: Sun Nov 03 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.