Introduction to Mockito-Method (Ii.)

Source: Internet
Author: User

Prefacethe previous "Mockito-method Introduction (i)" just introduced the first six on the use of the Mockito method, now we continue to introduce the last seven items, detailed reference to http://mockito.googlecode.com/svn/branches/1.6/ Javadoc/org/mockito/mockito.html official website.
The Chase7.Making sure interaction (s) never happened on mock-make sure the mock object has never been called
@Testpublic void TestMockito7 () {List Mockone = mock (list.class); List mocktwo = mock (list.class); List Mockthree = mock (List.class),//Mockone and Mocktwo are called, Mockthree no Mockone.add ("one"); Mocktwo.add ("one");// Normal call Validation verify (Mockone). Add ("one");//Add. ("two") has never been called verify (Mockone, never ()). Add ("two");//The following validation will fail because both Mockone and mocktwo have call Verifyzerointeractions (Mockone , mocktwo);//The following validation succeeds because Mockthree has not called verifyzerointeractions (Mockone, mockthree);}


8.Finding redundant invocations-looking for redundant callsVerifynomoreinteractions () is not recommended to the use of every test method. Verifynomoreinteractions () is a handy Asser tion from the Interaction Testing Toolkit. Use it's only when it ' s relevant. Abusing it leads to overspecified, less maintainable tests.--from official websitedo not misuse the Verifynomoreinteractions () method, only when needed to reuse, abuse will lead to poor maintenance.
@Testpublic void TestMockito8 () {LinkedList mockedList1 = mock (linkedlist.class); LinkedList mockedList2 = mock (linkedlist.class);//Using Mocksmockedlist1.add ("one"); Mockedlist1.add ("one"); Verify ( MOCKEDLIST1). Add ("one");//The following validation will fail Verifynomoreinteractions (MOCKEDLIST1);//The following validation will succeed Verifynomoreinteractions ( MOCKEDLIST2);}



9.Shorthand for mocks creation-quickly create Mock objects using annotations @mockimportant! This needs to is somewhere in the base class or a test Runner:MockitoAnnotations.initMocks (TestClass);--From the official websiteannotations are a quick way to create objects, and here we want to note that if you want to use annotations you need to initialize the annotations in the test class: Mockitoannotations.initmocks (TestClass);
   public class Articlemanagertest extends Samplebasetestcase {             @Mock private articlecalculator calculator;       @Mock private articledatabase database;       @Mock private Userprovider Userprovider;            Private Articlemanager manager;            @Before public void Setup () {           manager = new Articlemanager (userprovider, database, Calculator);       }   }      public class Samplebasetestcase {          @Before public void Initmocks () {           mockitoannotations.initmocks (this);       }   }



10.Stubbing consecutive calls (Iterator-style stubbing)-Iterative invocationsometimes we need to stubs with different return value/exception for the same method call. Typical use case could is mocking iterators. Original version of Mockito did not has this feature to promote simple mocking. --From official websiteSometimes we need to call the same method multiple times, each time we need to have a different return value (for example, iteration), we need to set a different return value/expectation for the same method, the attribute that returns different values according to the number of calls is Mockito later added. This is in fact the same as the last one mentioned in the 1th several coverage expectations.
@Testpublic void TestMockito10 () {LinkedList mock = mock (Linkedlist.class); when (Mock.get (0)). Thenreturn ("first"). Thenreturn ("Second"). Thenreturn ("third");//First Call, output "PRIMARY" System.out.println (mock.get (0));//second call, output "second" System.out.println (mock.get (0));//third and subsequent calls, both output "third" System.out.println (Mock.get (0));}



stubbing with callbacks-callback function as expectedyet another controversial feature which was wasn't included in Mockito originally. We recommend using simple stubbing with Toreturn () or Tothrow () only. Those should is just enough to test/test-drive any clean & simple code.--from official websiteThis feature is also not in the beginning Mockito, more controversial, it is recommended to use simple Toreturn () and Tothrow () to set expectations.
@Testpublic void TestMockito11 () {LinkedList mock = mock (Linkedlist.class); when (Mock.get (0)). Thenanswer (New Answer () { Public     Object Answer (Invocationonmock invocation) {         object[] args = Invocation.getarguments ();         Object mock = Invocation.getmock ();         Return "called with arguments:" + args.length;     });  Following prints "called With Arguments:1" System.out.println (mock.get (0));}



12.doThrow () |doanswer () |donothing () |doreturn () family of methods for stubbing voids (mostly)-void method common stubbing This is mentioned in the 5th of the previous article, there is a stubvoid method dedicated to void method invocation. Now these methods replace the Stubvoid () method.
@Testpublic void TestMockito12 () {LinkedList mockedlist = mock (linkedlist.class);d Othrow (New RuntimeException ()). When (mockedlist). Clear ();//The following call throws an exception Mockedlist.clear ();}



13.Spying on Real objects-monitor a real objectThe mock object's method is not to be called by the real, the spy is different, it is real to call that method, but you can also set the desired return value on some methods, if not set, it will actually call that method. If we had a service class, we would typically set the service as a spy object, and the DAO for that service call would be set as a mock object.
@Testpublic void TestMockito13 () {List List = new LinkedList (); List spy = Spy (list);//The Spy object can also set the expected value when (Spy.size ()). Thenreturn (100);//Use the Spy object to invoke the real method Spy.add ("one"); Spy.add ("one"); );//Output "one" System.out.println (spy.get (0));//Because we set the expected value for size, the following will output the expected value 100system.out.println (Spy.size ()); The authentication method calls verify (Spy). Add ("one"); Verify (Spy). Add ("one");}



Summary:the method of Mockito to the end of the basic introduction here. These examples can be downloaded here. Follow-up will be introduced in the work I am if the application Mockito.

Introduction to Mockito-Method (Ii.)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.