Introduction to mockito
Mockito is a unit test framework that requires JUnit support. Many dependencies exist in our projects. When we test a service-related interface or method, in most cases, there is no way or it is difficult to add all the dependencies, because this will certainly involve other business logic. In the development process, this module may not be available at all. So what? At this time, a mock testing method is emerging. Simulate the dependent object and set the expected value for the involved methods. In this way, you can focus only on the result of the dependent method to complete the unit test of this module. This method also refined the test granularity. . If you want to learn more, you can solve it by yourself.
Use of mockito
- First, a basic JUnit Test
@ Test public void stringutiltest () {Boolean B = stringutil. isempty ("good"); Assert. asserttrue ("must true", B); // asserted}
Such tests on tool classes generally seldom depend on other classes, so they are directly asserted. Of course, there are many types of assertions. Here we will try to use the assertions on Boolean.
2. Simulate the dependency of mockito and set the expected return value. The dependent methods have returned values. During unit testing, we do not want or recommend that you do not directly call the specific implementation of the dependent method, because the dependent method may not have been tested and there are bugs, is it necessary to write another test case for the dependent method at this time? Or is this method developed by someone else, but it has not yet been implemented. Do you need to implement it on your own? You 'd better say no! Let's see how it works.
Import Org. mockito. mockito; import Java. util. arraylist; import Java. util. date; import Java. util. list;/*** @ auther guozg */public class mocktest {@ test public void mockreturntest () {// mock creation creates the simulated object userdao mockedao = mockito. mock (userdao. class); userservice S = new userservice (); // create the tested class S. setdao (mockedao); // Add the dependency mockito for the tested class. when (mockedao. getdata (mockito. anystring ())). thenreturn (4 ). thenretur N (1); // set the expected return value for the simulated object method, Boolean B = S. checkdate (); // multiple thenreturn values indicate that Boolean b1 = s is returned for multiple calls. checkdate (); // if the expected number is less than the number of calls, the last call is returned if the number exceeds the limit. Boolean b2 = S. checkdate (); // if the expected number is more than the number of calls, then the corresponding value mockito is returned. verify (mockedao, mockito. times (1 )). getdata (mockito. anystring (); assert. asserttrue ("must true", B); assert. assertfalse ("must true", B1); assert. assertfalse ("must true", B2) ;}} class userservice {userdao Dao; Public Boolean checkdate (){
String id = "123"; if (Dao. getdata (ID)> 3) {return true;} return false;} public userdao getdao () {return Dao;} public void setdao (userdao Dao) {This. dao = Dao ;}} class userdao {public integer getdata (string ID) {return 0 ;}
}
Here is a simple example. I need to perform a unit test on userservice. checkdate. At this time, userservice is dependent on userdao. To isolate the implementation of userdao, use mockito. Mock to simulate the userdao object. The expected return value is set for the disabled getdata. Then, call the method to be tested, verify whether the expected method is set to be called, and assert the return value of the test method. The mockito. anystring () method is used to indicate that the getdata () parameter can be any string in the simulated state. Of course, you can also directly specify some parameters. If the parameters specified by the simulated object are different from those specified by the actual logic, getdata () in the actual userdao will not be returned () will not return the set expected value, but return the default value of the returned type, for example, int will return 0, Boolean return false, etc. Mockito also has many similar methods, such as anyint (), anyboolen (), and anycollection.
In addition, we can see the thenreturn () method. This is to set the expected return value for the dependency method. This can be controlled by ourselves. Then we can see that the settings can be set multiple times in a row. This is commented out in the Code. Because you are not confident in the language expression ability, let's show it in a table.
Then there is a verification method that is called mockito. Verify (). The parameters of this method are simulated objects and verificationmode. This verificationmode is a verification model, which can represent the number of calls, whether to call or not, timeout verification, and so on (some do not know what to do, we need to further study ). Verify () can be understood as an assertion.
3. For methods with returned values, we can control them by setting expectations and isolate specific implementations. But what about the method that does not return a value? Don't worry, mockti provides us with another way to control the behavior of the simulated object method, including logic processing, throwing exceptions, returning values, executing the original method logic, and doing nothing. Doreturn () | dothrow () | doanswer () | donothing () | docallrealmethod (); next, test doanswer (). First, we will add a setuser (User U) method in userdao, set the age for the user, and then call it through the checkdata of userservice. Then we use doanuser to control the logic of setuser.
Package COM. centnet. train. user. controller; import Org. JUnit. assert; import Org. JUnit. test; import Org. JUnit. runner. runwith; import Org. mockito. mockito; import Org. mockito. invocation. invocationonmock; import Org. mockito. stubbing. answer; import Java. util. arraylist; import Java. util. date; import Java. util. list;/*** @ auther guozg */public class mocktest {@ test public void doanwsertest () {// mock creation creates the simulated object userdao mockedao = mockito. mock (userdao. class); userservice S = new userservice (); // create the tested class user u = new user (); S. setdao (mockedao); // Add the dependency mockito for the tested class. doanswer (new answer () {public object answer (invocationonmock) throws throwable {user u = invocationonmock. getargument (0); U. setname ("ggg"); return NULL ;}}). when (mockedao ). setuser (U); mockito. when (mockedao. getdata ()). thenreturn (4); Boolean B = S. checkdate (U); mockito. verify (mockedao, mockito. times (1 )). getdata (); mockito. verify (mockedao, mockito. times (1 )). setuser (U); assert. asserttrue ("must true", B); assert. assertnotnull ("control failed", U. getname ());
Assert. assertnull ("the original logic is executed", U. getage () ;}} class userservice {userdao Dao; Public Boolean checkdate (User U) {Dao. setuser (U); If (Dao. getdata ()> 3) {return true;} return false;} public userdao getdao () {return Dao;} public void setdao (userdao Dao) {This. dao = Dao;} public void setuser (User user) {user. setage (12) ;}} class userdao {public integer getdata () {return 0 ;}public void setuser (User user) {user. setage (12) ;}} class user {string name; integer age; Public String getname () {return name;} public void setname (string name) {This. name = Name;} public integer getage () {return age;} public void setage (integer age) {This. age = age ;}}
We set only the age in userdao, but the asserted that the age is null is successful. This indicates that the original logic is not executed. Then let's take a look at the non-empty name assertions. This indicates that the setuser behavior is controlled by doanloud. Doanwser () needs to be passed in to an anwser object, which is a bit similar to a proxy object. If the call method has a return value, the Anwer () return value is it. Invocationonmock. getargument (0) gets the parameter, and then you can operate the parameter. You can try other methods, such as calling the original logic mockito. docallrealmethod (). When (mockedao). setuser (u ). Alas, at this time, the user's age will be available and still 18. important: For methods in the test class, you do not need to set the expectation and the original logic will be called. However, you must set the expectation for methods dependent on the class, otherwise, only the default value of the return type and the return value will be left blank.
Okay, after work, come here first. There will be new contacts in the future. The above example is a little rough. Please forgive me if you accidentally get into the trap! (It seems someone will look at it !!! It can be seen that the above examples can be used flexibly .)
Mockito unit test