Mockito Tutorial - Mocking With Junit and Maven

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi there welcome to this course on unit testing with mockito I am Ranga carnem I am a hands-on architect with more than 15 years of experience developing java web applications I have been using mockito to develop testable applications for almost a decade now one of the most important parts of being a good programmer is understanding how to develop testable applications mockito plays a key role in developing testable applications in this course you will learn what is a unit what is unit testing how can you do mocking with mojito and you'll learn how to write great tests with je unit and mockito all the code including the step-by-step details are in our github repository mockito tutorial for beginners the URL is in the description below the video this git repository contains the step-by-step details of what we would learn during the course 4j unit which is 2 L steps and 4 mockito which is 18 steps we will start with learning basic unit testing with J unit framework we will start with annotations a SERDES test suits and move into advanced concepts like testing exceptions how do you test for performance and how do you write parametrized us we would then move into mocking and see what is mocking and also what are the alternatives to mocking what are steps what are spies and why mockito is famous we would look into the different features of mockito the basic mocking features how do you verify calls to a method and a couple of advanced features like matches and argument capture will also understand how to create pies so we will use mockito j init runner and the mockito j unit rule we will integrate mockito with power mark to be able to mock static methods to be able to mock constructors as well and also we will use power mock 2 unit tests private methods the only prerequisite for this course is that you need to be a good Java programmer we will help you set up Eclipse and Java thanks for you interest in this course if you are ready then go ahead and click the enroll button you can also take a test drive and use the free preview feature I'm excited to share all my experience with unit testing and mockito see you in the course before we get started with the course there are three important things that you would need to know one is about the github repository second is how you can get started with installing Java and eclipse and the third one is the reviews feature let's get started with the github repository the URL to our github repository is github.com slash in 28 minutes you can google for in 28 minutes github and you'd be landing over there and this specific one is mockito tutorial for beginners this contains all the source code that we would be using as part of this course and also it contains details of all the different steps as well so j-unit we have 12 steps mockito 18 steps the github repository contains a section called installing tools there's a PDF here which would help you to install java and eclipse it's a step-by-step guide which would easily take you through installing Java and eclipse there's also a video to help you to install so you can actually follow the PDF step by step and try and install java and eclipse and if you have a problem then you can watch the video as well installing Java and eclipse is a very very easy thing so you should not really have any problems doing that the last thing we wanted to discuss was the review feature in some of the course platforms you might be asked for a review very early in the course if you are not prepared to leave a review you can click either close the pop-up or you can click the not ready yet button there you go those are the three things which we wanted to discuss during the short video if you follow the steps in the PDF and you have Java and Eclipse installed then you're all set we again welcome you to this course and hope you have a lot of as with all the in 28-minute tutorials and courses you'd start this one in a hands-on way as well so before we discuss a lot of theory about mockito we would start with our step one and try and set up a project where we can start discussing things much more so this is step one where we would learn how to set up an eclipse project with j-unit and marketer frameworks and we would end this step once we have a successful unit test if you have already followed the jn8 course and come up to here most of this step should be very easy for you so it should be a quick step where we get started with J unit and mockito I will launch up Eclipse you can enter any workspace folder in here I'm entering mockito August 2016 that's basically when I am creating this particular curve or you can click browse and browse to a specific folder the workspace is kind of the folder where eclipse would store all these files so I'll enter a workspace and click OK when you launch up a new workspace Eclipse would bring this particular window up I'm not really interested in this right now so I'll just close this and I would want to start by creating a new Java maven project so I would start with file new maven project mavin is very useful in maintaining dependencies with j-unit and mockito I would want to be able to use these frameworks I don't want to go to the repositories and download the jars and put them in the build path mavin is a tool which helps us make it very easy to manage dependencies if you have no experience experience with mavin that's not a problem at all in this course you'd be able to follow and understand what are the basic things about maven you can start off I am doing a cancel again so it's file new Mao and project or you can actually say file new project and type in mavin or the other way of getting this here is right click here and say new project and type in mavin so any of the type ways you would want to start that's okay so type in mavin we want to create a new project so new maven project and click Next so I'll choose the default workspace location the other thing is I would also want to create a very simple mount project so these two checkboxes you can check in and say next and one of the things with maven is you need to give a name to the project that you are creating so this is a new project I am creating so I have to name it and just like a java class we have a package similar to that for any project you need to have a group ID so I'll just put in comm dot in 28 minutes dot mockito as the group ID and the artefact ID as mockito example so you can actually put anything that you would want in here I am just saying convert in 28 minutes Marketo and mockito example as the thing so market of course and I am going to click finish when the project opens up on the top left folder you should see all these folders inside the market of course so you'd see source main Java source main resources so stressed Java and source stress resources typical Java project you would have all your source code in source main Java and all your tests in source tests Java that's exactly what we follow during RJ and it course as well so we write all the code in source main Java and all the tests in source tests Java in a typical maven project you also have a pawn dot XML Pollard XML is the place where you declare all the dependencies that you would want let's open the pom rat XML double-click on it and it would open this where I can actually click the pawn Road XML to see what's in there right now it's a very simple XML file there is not a lot of details in there there is a group ID artifact ID and version in this project we would want to learn J units and mockito so we want to use mockito so we would want Mowen now to download mockito and j unit for us how do we do that the way we do that is by adding something called a dependency so just go and add in dependencies and the dependency that we would want to add in our J unit and mockito I have made it easy for you by actually going in and actually making these dependencies available on the github so if you look at the step one this contains the dependencies section right here so you can actually take this dependency section and instead of typing in dependencies dependencies you can actually start off fresh and actually paste this in so what you do see right now is these dependencies will be downloaded and added in here that's the magic of moments enough you have these jars downloaded by Marvin and made available as part of mam and dependencies for this project and that's the beauty of Marin and that's the reason why we are using maven in this particular project so instead of downloading the j-unit jar and making it available in the build path what we are doing is we are using maven spawned or XML to download these jars and make them available for us we have a dependency j-unit and we are using 4.2 l version of j unit here and one point ten point nine version of mockito so these are the two dependencies which we added in and here are all the stuff that we would need to run this particular project so let's get started and start creating a small test to check whether everything is working fine so I would start with source test Java because we want to create a new unit us out created in source test Java right-click new I would want to create a test class so I would say test J in a test case and click Next and say new jn8 foltest that's good since you are already familiar with J on it I would go ahead and quickly create this particular test so I would call this first mockito test I mean there's nothing mockito in there yet and I would want to put this in the package comm dot in 28 minutes dot mockito and i would go ahead and click the finish button so this would create a small test for us and I will remove this fail I would add a simple assert as a true true this is a funny test because this is actually not testing anything but just to make sure that there is something being tested I had just added it in to have some fun and there you go so there you see the green bar again so the way I am running the test is right click run as J and it tests so that's basically what we are doing to run this test so what we have done during this step is that we actually created a simple moment project added in two small dependencies j-unit and mockito so Marketo is the thing that we are going to use in this particular course so we added the mockito dependency and also we wrote a simple test this test is not yet using anything from mockito yet we will start with using mockito very soon until the next step bye Heather welcome to this section getting started one of the most important things with mojito is to understand why we are using mockito to understand what kind of a context mockito fits in and to be able to understand that we need to set up our system under test we need to set up an example that we would want to test the example that we would be using is that to do service this is basically an interface you can kind of think of it as it integrating with some external web service or a / mq or some external system and getting it as a list of traduce and what we would want to be able to do is to provide business logic around it so what we'll do is we'll create a to do business I am PL which will use the to do service what we will try and do throughout the examples that we would be doing as part of this course is we will try and mob the to do service so instead of talking to the external systems we would mock this we would kind of make it return the values that we would want and using those values we would be testing the different methods which are present in to do business impl so that's the first thing that we would do is we would try and unit test this with a stub what we'll do is we'll create it to do service stub which kinds of Drayton's hard-coded values and we'll write a unit test using that so we'll write a unit is called to do business impl step test that we would do as part of our unit testing with stub example and once we understand system of the test once we understand how stubs can be used to write unit tests we will start really writing tests with mockito this is really going to be a slow but I think with mockito it's very important to understand the concepts of stubbing and also understanding the system and the tests so that we can write really good tests around it have some patience for the next couple of steps you would be doing a lot of setup and be doing a lot of basic work but when we start using mockito things will really get interest in the first step we looked at setting up the basic project for mockito let's start with the second step so what would we learn during this step first thing is we would start creating a simple example to understand why we need mocks so we will try and create a basic example and the basic example is a to do management application and this is not really the entire application as such we would really look at a specific part of the application and we actually want to create a to do management system and actually have some kind of a filtering around spring related to this so we'll create a simple example for that and we'll try and understand why we need mocks let's get an overview of the two important classes that we would create during this step one of the important things about this step is that this step is not really related to mockito at all by that I mean you're not doing anything related to directly related to mockito at all but this step is really important in understanding mockito very well to understand mockito you need to understand the concept of stubs and mocks and what are the differences between them and how do you choose one over the other and this example will set us in a good shape so that we can in the next few steps understand them in little detail the to do business impl and the to do service that we would be creating in this particular step our typical java classes there is nothing really special about them i would really request a little bit of patience for the next five minutes so that we can get through this and i promise in the next few steps you would really get started with understanding the base principles or mocking and stubbing and hub you can do this with mockito the first thing is an interface it's a to do service I mean you can kind of think of this as an interface which kinds of talks to let's say and to do management application let us say it talks to of wonder list so wonder list is a webpage website where you can manage your to-dos so let's say this will to do service drawer Java can talk to any to do management application and give the list of - dues for that particular user the important thing about this to do service is we don't have the implementation for it with us so this is an interface which we are making use of so this is an external interface for this particular application so that's to do service and what we are actually creating is we are creating a to do business impl this to do bs business impl what we want to see is how many to do's of that user are related to spring so let's say a user has 5 - dues but only let's say two of them are related to spring so what we want to give is a feature to the user to filter based on a specific topic so we want to create a method retrieve today's related to spring and it would call this particular method retrieve - duce and filters the one which are related to spring and gives them back to the calling method so let's quickly try and create these two methods what we do during this step is try and create this two methods step by step if you are in a hurry you can actually go to the github repository and copy these two files which are present in here so there is a to do business I am PL and there's a to do service your Java so those are the two files that we are talking about let's start with creating the to do service Java right click new interface and I would put it in a package called in 28 minutes data API the package will not really matter but I would really want to organize my code really well so I am putting it in comm in 28 minutes data API and I would want to call this to do service and I would say finish and the method I would want to declare in this interface is public list of strings so I would want to return list of traduce and the name of the method we should retreat to Deus for a specific user so that's the method that we are talking about I would need to import the list so I would go ahead and do that the way you can do that is control one or command one based on wherever you are and it would bring up the options I choose Java dot util dot list because that's the one which I wanted to make use of so that's basically the to do service and let's quickly go ahead and create the other class that I would need as well so the other class I would want to create is the to do business I am PL so that's basically the one so let's go here so this is the one which I would want to create to do business I am PL so right click new this time I'd circular us so I would put it in the package not in the data API I would want to put it in business and this is the impl or I can just leave it at business and I would give it to do business I am PL and I would click finish so in here I would want to make use of the to do service so what I would do is I would create an instance of the to do service in here so to do service to do service I can doall shift s and say generate constructor using fields so all shift s generate constructor using fields or you can manually create a constructor if you want to so basically what I am trying to do is create a constructor so I've never created a constructor for the to do service so to do business I am PL now accepts to do service and the most important thing that I would want to do in here is to create a method which would call the to do service to retrieve to those method and filter the ones which are related to spring so the method I would want to create is public it would also list written me a list of strings and this method I would want to call it as retrieve to do is related to spring and I would want to pass in string user as the input I would go ahead and press control 1 and import the list so now I have this but little thing so I would go ahead and add a return statement so it's written in null fair enough so what I would do is quickly create a list so I would start with creating a list of string two dues I'll call it filter to dues because those would be the ones which are after filtering so I'll create a new ArrayList and for now I'll just return this back what we want to do in this particular method is called the to do service dot retrieved toodles so I would call this with the user and this would return me list of tutors what I want to do is I would want to filter those which are related to spring so if you look at it right now so the to do service has a method called retrieved toodles so this retrieved reduce is talking to let's say there is an implementation of this which talks to wonder list or any of the to-do management applications and written we returns me back a list of todos from those toodles I want to filter those things which are related to spring so what I want to do is to filter those which are related to string so I'll say I'll loop around the to do so to do to use I'll just use kind of a basic thing here I mean this is not going to be a complicated algorithm as such so I just want to loop around the two dues I would want to start with if to do dot contains spring contain spring then I would want to add this to list of Toulouse so filter to use dot at so that's the retrieved to do is related to spring method so basically what we are doing is we are calling it to do service the implementation of this to do service is not really with us all that we have is an interface and the actual implementation is not available with us but the code which we are really writing is the retrieved - deleted - spring so what we are doing is whatever tools which are retrieved from the to do service we are filtering them for and looking for those which are related to spring so what we want to do is we would want to be able to unit test this particular method so what we want to do is write tests for this specific method so if I really look in terms of the terminologies which are to be used usually so this is the system under test so to do that business impl is what is typically called so here to do business impl is called SUT that the system under test if you look at the to do service this is a dependency because the to do business impl depends on that particular thing for being able to run and get the details so if i call this method then what do we we depend on we depend on the to do service so we depend on the to do service to go and get these list of users and then we would filter the users based on that so when we are writing the test for to do business impl the to do business impl is called the system under test to do service is a dependency and in the next couple of steps you would understand how we can actually try and stub or bog this dependency how can we write a unit test for to do business impl when we do not really have the real implementation of true service available the true service could be developed by some other team or could be an external interface I am talking - it could be a web service that I am calling and or it could be another team which is developing that service and that service is not really available right now so how do we able to develop or how do we able to really test it to do business impl without the to do service implementation being available so that's the problem that we would be discussing during the next couple of steps so what we have set up during this step is the base for understanding what is a stub what is a mock and we would look at those things in the next couple of steps I know we are doing I understand that this is a little slow start to the course and we have not really discussed a lot about mojito yet have some patience we would really get started with mojito in the next couple of steps the most important thing about understanding the most important thing with mockito is understand link why we need mockito and understanding the problem it is solving I am sure that these two steps which we have done until now would lay firm ground for us so that we would understand mockito in a really good way so thanks for your patience and I'll see you in the next step welcome to the third step of this market of course thanks for the patience that you should in creating this small example in the last step and in this step we would try and test the last example with a stub so we would learn what is a stub and we would create a unit test with a stub and we will understand what are the disadvantages of using stubs to just get an overview of what we did so we have a to do service which is the dependency of this particular class this true service is being implemented by some other team which we don't have access to but we would want to be able to test the to do business impl what we would need to do is to create some kind of a to do service so one of the things that we can do is create something called a stub a stub is nothing but a sample implementation of this particular to do service so I can create a stub class which implements this particular interface so what we will do now is we will create a stub for to do service and we will try to use that stub to test it to do business I am PL so there are basically two steps that we want to do so the two steps are one is create true to service stub and second thing is test the to do business impl using the to do service stub let's start creating the to do service stub very quickly so since this is a stub I don't want to really create a stub in the main codes I mean I don't want the stop to be included in main code so what I'll do is I'll create this tab in the test Java and I would kind of use this same package structure so it's gone into eight eight minutes data API so I'll say right-click new this would be a Java class and I would want to do comm in 28 minutes package would be same as the original class data API and I would want to call this class to do service stop stop is nothing but a class which returns some kind of dummy data so go ahead and I would want to implement so I'd want to create a dummy implementation of the to do service so I'll say implements to do service there's a compilation error why is there a compilation error because the to do service has this method the to do service has a method relative to do switch we need to stub now so let's say now add unimplemented method so this would create a dummy to do service method or you can manually go ahead and create this method as well public list string retrieved to do so instead of returning null what I would want to return is an ArrayList with a couple of values in there so that I can use this as a stub for testing the to do business impl so what I would want to do is create a arrays dot each list is a very useful arrested as list sorry the very useful function so if i want to create two items one comma two so arrays dot as list one comma two would create that for me so this would create a list of these two and return it back what i would want to really give is little bit more useful values so i am giving a list of toulouse so I'll enter a little bit better values than one two so I am creating learn spring MVC learn spring learn to dance as the list of to do that I would want to retrieve so this is a dummy implementation you can see that this to do service we are creating a dummy implementation for that so this is a stub so this is a sample implementation of the to do service I'm I'm not really talking to the service at all I'm actually hard coding values and returning them back so that now when I'm testing the to do business I am PL I can make use of this stub so now let's try and test the to do service to do business I am PL so I would go to right click and say new other other and I would type in test so I would want to create a new unit test case or neck I can say which package I would want to put the test in I'll use the same package as the original classic on dot in 28 minutes dot business that's where the original class is and I would want to call this to do business I am PL because I am going to use us I'm using a stub here I will call it impl stub test and click finish as is usual a sample test is created for us so what I would want to do now is I would want to be able to use this stub to do the testing for to do business impl so first thing is I would want to create to do business impl so to do business impl let's create a to do business impl to do business I am PL is equal to new to do business I am PL so to create a to do business I am peon I needed to do service so let's go ahead and first create a to do service to do service to do service to do service I would want to create a to do service is equal to new what we want to make use of in this test is the new to do service stop so I'm creating a to do service stub to be really specific compilation error I have to input this in to be really specific I'll actually rename this so I will call this to do service step so the shortcut is all shift are or you can actually do right click refactor rename so that is one which you can use to change the name of a variable so I have renamed this to do service stub and I'm now created at reduce business impl with the to do service stub so now we can use this stub to test the method so I would want to call the method to do business I am PL dot retrieved to delete it to some dummy user I don't really care who the user is because we are hard coding the it in disturb and I'll take this and I'll put it in a local variable so list filtered to Deus that's basically it so since this is a unit test what we would want to be able to do is to check the filter list of tutors so what we wrote what we did introduce service tab is that we put in one two and three and out of which only two are related to spring so I would want to check whether the list which is returned back contains only two values so let's do that how do we do that we use the assert equals assert equals the first one is expected so we want the size of the filter to dues to be to I would want to give a better name to this so typical naming convention is test and the method test retrieved to Deus related to spring I prefer using an underskirt to say using a step so this makes it clear that this particular test is using a stub to test that here it's already we are putting it here as well so it's a duplication depends on whether you like it or not so I'll do right click run as J unit test so there you go now we are able to test this particular thing using the stub so we created for this stuff for the to do service we created a stub and related return dummy values and we use those dummy values to check whether this is particular this is working or not so this is how you can create a test using a stub for anything that you depend on so this to do business impl depends on to do service and what we are doing is we created a stub called to do service stub and returned dummy values back so now this is good so we are able to write this test I mean this is a good test we can improve this test further to not just look for this size but to check whether the eggs exact to lose are populated or not that I would leave as an exercise for you so if you look at the exercise one of the exercise would be to improve the assert for the ArrayList so right now we are just looking for this size whether it's two but actually we can test much more so what we can actually check is whether the two items in the array list are these two so that I would leave as an exercise for you to do what we want to really focus on is what are the advantages and disadvantages of using a stub to test so now this tub is nothing but a real java class so let's say I want to create another test case so here this particular test case I created where this tub is returning three values but let's say I want to write another test case where this particular method is returning only one value back or its treated it's not retaining anything back so I want to create another test wherein I would want to check for a scenario where I am passing empty like when I am getting no values from this service using a stub I will just call it - let's just say dummy thing so it's not really mad doesn't matter what I call it but in this test I would want to actually check whether when there is nothing returned back from the service where there is nothing coming back from the business impl as well here what one of the options I have is I can pass in a dummy one and then I have the user so I can say if user is dummy then return this if you else user is dummy one return something else back now you can see how complex that kind of a code can become so as an when I need more things then I would need to keep adding logic to my stub so the stub class will start growing a lot the other problem you would have typically when you're using stub is the fact that let's say in addition to this there is another method which is coming in so let's say in this particular thing I'm adding a method string user and let's say there is a new method instead of retriever to deuce I would say configure something for a user there's a new method in the interface what you would see is this tab now you need to create the new method in this tab as well because disturbed implements it to do service it needs to implement all the methods which are there in this service so this is the other problem so you need to start having a lot of maintenance headaches because you are using stubs because stubs are nothing but real like a dummy implementation of the interface whenever you add a new method delete a new interface or anything of that kind you need to keep maintaining this stub as well so the two main problems with using a stub are dynamic conditions so when I want this particular method to return different kinds of values in different kinds of scenarios then it becomes very complex code so this code will start becoming very large and difficult to maintain steps are useful in very very simple scenarios but in most of the projects we use something more dynamic called mocks we will get introduced to mocks in the next step in this step we looked at a sample test using a stub we saw how to create a test using disturb and also we looked at what are the problems that we usually face when we write tests using stub in the next step we would start using a mock until then bye welcome to the step four of mockito it's time to say hooray this is the first step where we will really use the mockito framework in the last step we looked at what is a stub and what are the disadvantages of using a stub so what we'll look at in this particular step is what is a mock how do you create a mock with mockito and you will see a lot of advantages of using mocks so let us get started before we get started in depth one of the things that we would need to make sure is to be able to easily import static inputs what are static importantly to do business impl test we used assert equals and the SL equals is actually a static method if you look at it is a static method which is declared in the SL class so this is inside the org dot J unit Ezard class so we imported the static import or J unit SL dot star so if you look at the test what we do is we would have imported this in so if I don't do this so if I am NOT importing this then you would see there's an error and if I go and press control one or command one on this you would see this is a suggestion which is brought in to add the static import automatically however this suggestion does not come up for all the methods automatically because J unit is one of the standard frameworks which is used across the Java world it is automatically coming up because that's how eclipse is configured to do it but if you want other methods belonging to mockito to come up in this way you need to do a little bit of configuration eclipse in Windows then you need to go to window preferences I am on Mac so I do Eclipse preferences if you are on Windows then you need to do window preferences and this would open up and oh here you can type in favorites if you look at favorites there are two things coming up Java editor condenses and JavaScript we are really worried about the java part of so I will click favorites here down here I can define a list of static members that we can use so the content assist content assist will propose these static members in that particular case so if I type in a method from one of these classes then it would automatically suggest to import this static member so what are the classes I would want to add there is a list of these classes which are present in here so or generate result is the default one which is already being suggested but the important ones are mockito BDD mockito matches and core matches from the start again so it's Eclipse preferences or window preferences so and then type in favorites be careful with the spelling and then you need to choose this one under the Java tab and keep type so click on new type and it would break up bring up a thing and you can type in mockito and click browse so when you say mockito it would bring up this class so the class which we would want to add is mockito that's one and then I would want to add a couple more classes which we'll be using in the subsequent steps let us do this once so I'll click in new type and type in mockito actually I want to type in B DD mockito so that's one of them and let's add a couple more quickly they're all right here so I can say matchers and add it in and I can add it the core matters as well so there are basically four classes that we are adding in we learn about this clan crest classes very soon don't worry about them they mockito related things that we added in our mockito and BDD mockito so the way you add them in is very simple so you click new type and say browse and type in mockito and then they would be this class coming up if you type in BDD mockito this would be coming up and the other ones are hamcrest matcher so you just need to type in matches and core matches and add them in and say apply and say ok that's it so this would make it easy for you to follow the entire course because as soon as you type in the method eclipse would autosuggest the imports so don't need to really remember which particular class has something all the time so as soon as you type in a method then eclipse can automatically suggest the port now let's get to the actual thing that we want to do as part of this step the actual thing we want to do as part of this step is not to use a stub but to use a mock so what I will do is I will copy this test so I will copy ctrl C or right-click copy and ctrl V and I will rename this method to do business impl instead of using a stub i want to use a mock to write the test so I'll say mock test what we are doing here is that we copied the code so it's actually right now using a stub so I want to actually use a mock so I would want to be able to use this mock this one is using the to do service stub so instead of this I would want to use a mock what is a mob in the earlier step we created a stub so we created to do service stub the to do service stub is really a hard-coded class so it's basically like a hard-coded class which kinds of implements the entire thing that this interface defines and there's a method which returns some dummy values back it's very difficult to maintain this code because this is really live code and whenever there is a change in the to do service then we need to change all this stuff so what is a mock in that particular sense so instead of creating a real live class there are frameworks which would allow you to create a dummy class or a mock class for that specific interface so you can say I want to create a mock for this particular thing so I want to create a mock for to do service so give me a mock so what this would do is this would return a class or I will just say to do service some mock class or mock to do service and give it the to do service dot class so what we can do what the frameworks allow me to do is they would be allowing me to say okay when this particular method is called so let's say on the mock to do service a retrieve to do method is called with some parameters or some parameter some value then what you want to do in this particular thing is stop this particular thing so what you do is make this return of value so here what we are doing is instead of hard-coding a class so instead of creating a stub class and making it return a list of values what we are doing here is we are actually dynamically doing it through code so what we are saying is create a mock for this particular service and when this method is called on this service then written this value back so there are frameworks which allow you do that so this is more a dynamic behavior so this is not static behavior because I am defining as part of my code what should be the return value for that particular method which class should i mock which class should this mock behave like so all that is pretty dynamic so there are frameworks which allow you to do this kind of things and this is what is called mocking let's look at an example of mockito and let's discuss what is a mock in detail a little later one of the things you would see is that mocks offer much more functionality than stubbing you can ask how many times is this method called is this method called at least once mocks offer a lot of more functionality than stubbing but will come there when we finish one example with mockito let's focus on getting this particular test running with mockito so what I want to do is I don't want to use a stub but I would want to use a mock right now this is using a stub but I would want to change it to use a mock so I'll go ahead and rename all shift are or right-click refactor rename so I'll say to do service and I am a head of the time because I am still using this stub and I'm calling this a mock but that's ok so to the service mark is equal to instead of saying new to do service tub what mockito offers is a method called mock so I want to mock which class I want to mock to do service class I want to mock to do service dot class so I want to mock to do service class so I would press control one or command one and I would add the static import for mockito so Mach is a method in the mockito class so if you look at it so this is a mock class or I can create a mock object of a given class or an interface so as you can look here mockito can be used to create a mock object of a class or an interface this mock method would create a mock object for that particular class or an interface which is passed before we do anything more I would want to really read debug this method and see how the mock is working so I'll say right click debug ass J unit tests yes please I would want to switch to debug perspective so you can see the objects sorry the variables which are being created right here I am in the debug mode enough so I can do so I can go to run and see all the different options that I have step into step over step written and all that kind of stuff so what I want to do is step over here so I just press f6 so I'm calling the mock method inside mockito so what does it create it creates a service mock so you can see that there is an object created it's called to do service enhanced by mockito with something cg lib or something but the most important thing for you to understand is the fact that this is using a mock this is no longer using a stub but this is actually using a mock from that particular thing so now what we are creating is we are creating it to do business impl with a particular mock so I am passing the mock to that and creating it so let's create it to do business I am PL so I will keep pressing f6 so to go into now I would want to understand how the filter Toulouse method is working so I would want to see what is happening in there so I will press f5 so I will go ahead and press fi here so that I can go inside the method and see what is happening I am inside the retrieve to do is related to spring method I am passing in a user object but the most important thing for you to realize here is that this to do service is a mock so this to do service which we are passing in is actually a mock let's see what value is returned back so I'll go ahead and keep pressing f6 to step and I would want to so now we are calling a method retrieved to use on the user mock so on the to do service which is a mock we are trying to column method retrieved toodles actually when we wrote the code for this we didn't tell the mock to do anything so we didn't say what should happen when retrieved to doze is called let's see what would it be returned back so I will press f6 again if you see the list of traduce it's an empty list so what is happening is that the to do service which is a mock which we are passing in is actually returning I mean when the method is called on the mock it's returning an empty list when we did we did not tell it to do anything so it's returning an empty list back this is one of the good features of mockito framework this is these are called nice mocks by default mockito create something called nice mocks so this nice mocks when a method which is not declared or which which is not explicitly stated is called on the mock it would return a default value back as you can see here it's written in an empty list back so what would happen here is that so there is no to do to loop over so it would skip the loop and it would actually go back and it would written an empty list back so if you look at the filter to deuce what does it have empty because there is nothing in there so this assert would fail obviously because it's checking for two so this would fail so I'll go ahead and I am no longer interested in what's happening so I will go ahead and do ratio so f8 so you would see that the test would fail but the most important thing if you look at what we have learnt as part of this particular test is the fact that I've created a mock so all that I did was create a mock I am not using this stub here so I am just creating a mock and the mock by default is returning a dumb empty list back so that's good so now what I would want to do is I would want to define this mock to return the values that I want it to return so let's go ahead and do that so what I want to do is when to do service dot this particular method is called so which method we already have a stub class right so so we want to do something really similar to disturb for so when retrieve deduce method is called on the mock what we want to do with the value dummy retrieve reduce is called with the value dummy what we want to do we want to return a array list with the specific values back so the specific method which does that in mockito is stub you can also call it when so there is also method call when so I will start with when so I will put when and control one or command one it would say add static for market event so when this particular method is called what do we want to do we want to then return what do we want to return the value which we want to return is what values are labeled in this step so I want to return these values which are already defined in this stub so I will go ahead and copy them and create a list with them so I will just say I will just create a new list and I would return that list back so what would happen now is when this particular method is called with this value then what is the value that is returned back then tools are returned back so you can actually try and debug this and check how it works I'll directly run this test this test now succeeds because what we have now have done is instead of the stub so instead of using this stub we are using a mock so we have nuf defined a mock and we made the mock when it is called with a specific method to return a specific value so when the to do service mock is called with a dummy value it has to return these to do back so in these three lines of code we have created something very similar to this stub that we had created earlier so if you look at this tub so this is what this tub did so we had to create a real class to do that instead of that what we did now is to actually define what to do in the mock so the most important advantage of the mock is that now I can make it return different values so if I want to really write a new test so I can go ahead and create a new test so instead of calling using a mock I will say with empty list so all that I need to do is copy the earlier and I will say with empty lists and I can say air alert as list should return nothing back so empty list or I can create a new ArrayList here to return that particular thing back and now what would I expect because I am giving an empty list I would expect zero back now this particular test also would pass so right click run as J unit test this one also passed so both the tests are now passing so now I'm able to test two different scenarios without really having any complex logic at all doing this with this kind of things which stop would be really difficult but with a mock this kind of things are really easy so do you think which we learn during this step is how do we create a mock so the first thing which we learnt is how do we create a mock so we use the mock method which is defined inside the mockito class so this creates a mock object of the given class the other method which we made use of is when so when is used to stub a method so we want to stop this method call with the return value so then return is the one it sets a return value to be returned when a method is called so when in combination with ten return so when this method is called with a specific value then return this thing back so then this particular value is returned back so I am using that mock to test the to do business impl so we call the actual method and check whether the values that are written back are as expected and you can also see how flexible it now becomes enough I can create a different test with a different return values I can make the method return that value back and I can test whether these scenarios are working fine so that's the flexibility that a mock brings in so you can do different kinds of tests using a mock we actually covered a lot of things in this particular step so I think it's very good if you can take a break and try and redo the entire step one of the important things that you can do is play around with code so out really recommend you to debug the whole thing try and play around with the mock try and put debug breakpoints at each one of the places and try and debug to see what's happening inside and one of the things that you can also think of is what are the generate best practices that we are not availing to there are certain things that we are not really adhering to at this point we'll slowly change that phone of the focus one was on getting you to learn mocking stubbing and things like that so there were a few generate best practices that we were not following so try and see if you would be able to identify them for enough and also make sure that you visit the mockito official documentation so there is a link down here on the github step 4 page which points to the latest mockito documentation so you there's a lot of stuff down here so if you are really interested you can go down there and say check what mockito is all about so those are the exercises for this particular step try and spend some time repeating these steps and do the exercises and I will see you in the next now that we have a little bit of familiarity with mockito we can go into the basics of mockito cheering the next step we would try and mock the list interface AHA I call it a class it should have been mocking list interface what do you do is we would Mock the list interface and we would kind of try and do a different things around it we would try and if three see if we can return different values on subsequent calls we will talk about something called argument matches we will see how to throw exceptions so you are going to use list interface a lot and after that we would try and play around with the BDD style but it is a very interesting style of writing your test so we would try writing BDD style test with marketer and other than mocking methods with mockito you can also verify for specific method is called on a mock so is this method called is that method called is this method called with this argument so those are the things that we would do as part of the next sequence of steps I am sure you are in for an interesting ride let's get started after a long step for welcome to this step 5 in this step we would learn a few more keto examples we will do a few more examples mocking the list class so list is one of the interfaces in the java.util package so we will take that list interface and will try to create mocks for that particular class we would return multiple values from a single method so is that really possible yeah with a mock it's really possible and you look at how to use argument matches and we would also look at stub method and how you can throw exceptions from a mock so those are the different things that you would learn as part of this step we'll take a look back at what we did in the previous step first so what we did in the previous step is we were able to mock the to do service class so we created a mock for the to do service class using the mock method and what we did was we made the to do service mock . retrieved ruse so basically we are saying to do service mode when retrieve reduce is called on you with a value called dummy then return back to this the way we do that is we would use the van method so when this particular method is called then return this so that's basically what we made use of to return a specific value from a method call on a mock so this method call on this mock will return this value when this argument is passed to it so that's basically is this is what is called typically stubbing a method so this is dynamically stubbing a method actually this is not really hard coding stuff so i'm not really creating a method like that but we are actually doing that dynamically so this is creating a mock this is making the mock return a specific value on a specific method call that what we look we looked at in the previous step so let's start with trying to mock a list interface now so what I will do is I will go and reset my perspectives a window open perspective and al-mu to Java I'll go to my favorite perspective for writing code so that I can go to the test Java so now I would want to create a new class so I would want to create a new test for the list interface I'll start the usual way so right click new other and I can type in test J on a test case and I can say list test and I would just say finish and I would not worry about it I will remove the failed line and I would get started so I would want to mock the list interface so what is the way I can mock a list interface mock of list dot let's input the list class I would want to Java util list and also enough I can actually see that list mock is now declared what we want to do is I would want to actually mock the list mock dot size method so I would want to mock the list dot size method and I would want to return a value too how do I do that so what I would need to do is when this particular method is called what I want to return back I would want to return back a value too so when this particular thing is called then I would want to return a value to chur let's write a quick j-unit to check whether the mock is working fine the set equals I will call list mock dot size and see if this is returning the right value so let's also control one add static input for asset dot start so let's run this test quickly right click run as JUnit test all shift XC ctrl f11 whichever you want where you won't want to and this particular test is running fine enough so let's call this method let's one of the important things is you don't really need to call every method with a test just like with early versions of j-unit it was important that a method the name started with test because that used to signify unit tests but now with the add tests annotation it's not really important so you can call it anything some people still would want to start with test more the traditionalists out say but for me I don't really worry about it so let's call let's mock less sighs method I'm just renaming it to make sense to me so let's mock the size method so that's what we did so we mock the size method to return a value we wanted to return so whenever you call list dot size how many other times you would call list dot size you would get the same value back so let us check that up I am calling the method three times now and you would see that the test succeeds so each one of those times the value which is returned back is two so now I would want to actually create multiple return values from a particular mark how do I do that so let's mock list size and I would want to return multiple values back so the first time I call it I want to call a specific value and then I would want to greet on something else Oh dot then return three so let us see this awesome which line is failing let us double click here so the second line is failing because it is returning a value not to the first time it returns a value to the second time it would return a value three so the way we are saying it is when list dot size then return to so the first time list dot size is called we return back to the second time it is called it returns back three so now let us run the test and see if everything works fine there you go so now it works fine so the first time list dot size is called it returns to the second time it is called it would return three back okay now that we assert macht list dot size I would want to go and mock list dot get method so I would want to mock the list dot get method so let's mock the list get and I would want so I would want to mock the list class but I would want to mock the gate method so dot get method for the get method I need to pass a number so the way I would pass it is by putting in a 0 so when gate of 0 I would want to return back not this let us say I would return a string back I will just say in 28th let's see what would happen so when listed gate of zero what would I get back when I call that method an amok I would get back in 28 minutes all shift xt a transit test what is more interesting for me is what would happen when I check for a list of gate of zero so if I do instead of gate of zero I would do get of one so I have not Mach set any value for this what would happen is the nice mock behavior would kick in so what would happen is this would return a value null so when I call a nonstop the method so this is really a method which I am NOT disturbed so you would see that it does succeed because this is actually working fine so if I didn't do this if I didn't do get of zero then probably this one would also would have returned now that's basically the default nice mock behavior of mockito one of the important things is in earlier mocking frameworks I mean easy mock was a famous mocking framework before mockito and in easy mock there was no like this easy mock this nice mock behavior was not really a default so by default if there is any method which is invoked the expectation for which has not been set earlier the test would start failing that was one of the things with easy mock which I didn't really like because it kinds of creates a lot of brittle tests because but with mockito nothing like that so it's it kind of assumes a default functionality when so it it's the nice be nice mock behavior is the default so it kinds of returns null or empty lists or default values when a method is called so when an expectation is not set and that particular method is called mock Tito is much much safer so it's much nicer so I quickly under the changes and I put the stubbing back so when let's mock dot get 0 is called we are rooting in 28 minutes back and I am asserting in 28 minutes in here let's say every time list mock dot gate is called I would want to always return in 28 minutes irrespective of the parameter that is passed that's where things like argument match comes and so this is called an argument matcher so what I want to do is any thing so instead of zero I would need to put something called any int I just need to say any int and any int is one of the things which is present in the market or class so probably we would need to do a static input I am not sure why it's not picking up so let's manually add a dot any int so we can actually make this a star and any in this knob automatically detected so any int is what is called an argument matcher if you click the documentation of it the method does not do any type checks it is only there to avoid casting so this is basically any int so this would match any int so if this method is called with any integer or null or anything so then it would return the value back so what you would see is even the second value would return back in 28 minutes that's a quick test ah okay that's great sir whether you are calling it zero whether you got in calling with one or any other value this should always return in 28 minutes back this concept is called argument matchers so if you look at the mockito class and do any the Macchio class extends matches and in here you would see that there are a lot of any things so you have any boolean bite care in long so any of these so any collection anywhere arc or any string any list so you can even say something called any object so instead of any int I could have said any object then it would have met anything that is passed to that specific method so you can use it for any specific class so or you can say anything of specific class as well so these are all the different our argument matches which are defined by mockito and these are the different things that we could have used here as a matcher so because here the value which is being passed is an integer I am saying any int if it was a string I would have said any strain so based on that you can use the argument match the next thing I want to do is to make this method throw an exception so when this mock thought get any method then I wouldn't want to return anything but actually I want to throw an exception so dot then throw so this would throw a new runtime exception of something so this will mock the list get to throw a runtime exception so what I can do is I can actually instead of assertequals this will not work anymore because the list mock would throw an exception so I would just do list dot get of zero and I would use a J unit feature so how do you test exception with Janet so I'll say expected is equal to runtime exception dot class so this would check if an exception is thrown so let's see right click run as J in the test so as you can see this test succeeds so what is happening is when this mock is getting called with any integer this would throw a runtime exception so here I'm really calling the list mock dot gate of 0 and this would throw an exception and so this is catching it so if you you will see that if I don't have this in here then this test would fail so I am doing a right click run as J unit test without the expected tag and it's saying that runtime exceptions something so this is throwing a runtime exception something so this test starts failing so to prevent it from failing I would just add an expected tag in here so that's basically a lot of methods that we have stabbed as part of this particular step so we started with making a single return value from the list mock and then we return multiple values and then we use an argument matcher to returns a specific value from the list or gate and then we move into argument matches and we also discussed how to throw an exception so those are the different things that we discussed as part of this step until next step there is one question we are frequently as what do I learn next hour in 28 minutes course guide has the answer to that question think about this for a moment what gives more satisfaction to a course creator lots of money yeah he does but what else great reviews yay that's it for me the happiest moments are when I really receive great reviews and we had 1500 such moments in the last eight months so that's 1500 five-star reviews in the last eight months alone thank you for that these reviews really reflect what we wanted to achieve when we started in 28 minutes there is one question we are frequently as what do I learn next hour in 28 minutes course guide has the answer to that question it has the details of our most popular free and paid courses you will find a link to it in the description of the video let's take a quick overview of the different courses that we created for you as Kevin says the Java EE made easy code gives you the big picture there are a lot of pieces that make up the Java EE and this course should help you to understand how all the pieces fit together spring MVC course takes you through a journey of building a web app in 25 easy steps as alexander says we follow the 2080 principle and take you through a great journey with java servlets and JSP building a java ee web application in 25 easy steps mavin is the dependency management framework used in more than 80% of the projects this call take you through a journey with mavin with real-world examples and we have courses on C for beginners and also see puzzles for interview preparation we have a huge list of free courses as well spring Eclipse j-unit design patterns Java tests Lyon development transaction management JavaScript Java collections mojito and we are number one on YouTube for Java interview questions good luck with your learning always remember that the best way to learn is by doing you would never learn riding a bike by just watching somebody do that similar to that learning programming is all about getting your hands dirty keep getting your hands dirty and good luck
Info
Channel: in28minutes - Cloud Made Easy
Views: 496,436
Rating: undefined out of 5
Keywords: Mockito Junit Tutorial, Karanam, interview, Mockito Spring Tutorial, Rao, Ranga, Mockito Tutorial for Beginners, Mockito Tutorial, rithus, Mockito Maven Tutorial, in28minutes tutorial, in28minutes, java
Id: d2KwvXQgQx4
Channel Id: undefined
Length: 71min 53sec (4313 seconds)
Published: Mon Sep 05 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.