Home arrow Tutorials arrow Mock Controls with EasyMock
Mock Controls with EasyMock PDF Print
Most people who have used EasyMock before are familiar with the types of mock objects. There is the basic mock object, created with EasyMock.createMock(MyInterface.class). There is the strict mock that validates both the method calls and the order they occur. Finally there is the nice mock which returns a basic default (false, 0 or null) if an unexpected method call occurs. However, most developers I have come across don't use mock controls much. This tutorial will introduce you to the concepts of mock controls and show you an example of where testing without them may not be as safe as you think.

The Example

Mock objects validate the execution of method calls across a single object. However what if you have a scenario where the order of method calls matters across objects? Take the example below:

...
public void runReport(int userId) {
     // load values by userId and where Active Flag = Y
     ReportRecords records = reportDAO.getActiveUsersByUserID(userId);

     // generate report based on the records returned
     processReport(records);

     // Removes users after reports have been run
     userDAO.deleteUserByUserID(userId);
}
...

If I went to refactor the above method and switched the calls to

...
public void runReport(int userId) {
     ReportRecords records = null;

     // Removes users after reports have been run
     userDAO.deleteUserByUserID(userId);

     // generate report based on the records returned
     processReport(records);

     // load values by userId and where Active Flag = Y
     records = reportDAO.getActiveUsersByUserID(userId);
}
...

the report would no longer work because we would delete the users before running the report on them (nevermind the NullPointerException that may be thrown from processReport). In situations like the one above, the order of method calls across objects matters. So how do we address this issue with EasyMock? Enter mock controls.

The Wrong Way To Test

Mock controls allow you to couple mock objects together. Now, coupling is usually considered a bad thing in software development. However, in this case, we need to have a relationship between mock objects so that we can establish who's methods were called first. Let's look at a test case for the above scenario without mock controls first.

...
public void testRunReport() {
     // class to be tested
     ReportRunner runner = new ReportRunner();

     // create and inject our mock objects
     UserDAO mockUserDao = EasyMock.createMock(UserDao.class);
     ReportDAO mockReportDao = EasyMock.createMock(ReportDAO.class);
     runner.setUserDao(mockUserDao);
     runner.setReportDao(mockReportDao);

     // record our behaviour
     expect(reportDAO.getActiveusersByUserID(123)).andReturn(new ReportRecords());
     userDao.deleteUserByUserID(123);

     // replay our behaviour for the test
     EasyMock.replay(reportDao, userDao);

     // run the test
     runner.runReport(123);

     // verify the results of the test
     EasyMock.verify(reportDao, userDao);
}
...

Now if we actually try the above test case, we will find that it will pass for the first example. The issue arises when we try the second example. It still passes. This test doesn't truly verify that our refactoring hasn't broken existing code (one of the advantages of unit testing in the first place).

The Right Way To Test

Let's create a test case using mock controls to address the issue.

...
public void testRunReport() {
     // class to be tested
     ReportRunner runner = new ReportRunner();

     // create our mock control
     IMockControl mockMaker = EasyMock.createStrictControl();

     // create and inject our mock objects
     UserDAO mockUserDao = mockMaker.createMock(UserDao.class);
     ReportDAO mockReportDao = mockMaker.createMock(ReportDAO.class);
     runner.setUserDao(mockUserDao);
     runner.setReportDao(mockReportDao);

     // record our behaviour
     expect(reportDAO.getActiveusersByUserID(123)).andReturn(new ReportRecords());
     userDao.deleteUserByUserID(123);

     // replay our behavior for the test
     mockMaker.replay();

     // run the test
     runner.runReport(123);

     // verify the results of the test
     mockMaker.verify();
}
...

So what is different? In the new test case, we are using a strict mock control (mock controls have they same three types as mock objects: regular, nice and strict) to create our mock objects. By doing this, EasyMock will not only verify that the methods we record were executed, but in the correct order across objects. You should also notice that the recording of the behavior has not changed. That is all the same. Finally, instead of having to specify all the mock objects to replay and verify, our mock control kept track of what was recorded where so all we have to do is tell it to replay and verify.

When you try the new test case, it will pass for the first example, but fail for the second. Our refactoring safety net has been cast and we can refactor at will.

Conclusion

So when do you use mock controls vs mock objects? Mock controls are great for maintaining a relationship between objects. I personally also think the code is a bit cleaner given that you don't have to list out a long list of objects to replay and verify.

I hope this helps you in your unit testing endeavors. Questions and thoughts are always encouraged in the comments!

127 Responses

  • intrigued responded:

    Is anyone actually using this in the wild with success?

  • Michael responded:

    Ingrigued,

    I've used it at my past two companies and I know of others at my last company that use this on a regular basis. Any particular concerns you have on the approach?

    Michael Minella

  • M Yousaf Sajjad responded:

    We also use EasyMock in our company for unit testing

  • Phil responded:

    Hi,

    Full link with source code into an ZIP file will be cool.

    Regards
    Philippr

  • Replica Watches Outlet responded:

    Rolex is undoubtedly a model title recognize which is usually acknowledged and honored throughout the globe.

  • cheap imitation watches responded:

    watches are amazing they're able to cause you to look fantastic just when gown your self in compliment your character.

  • Sd responded:

    Hey moron,

    add dates to you blog posts so we know it's still relevant or not

  • http://thehampdens.com/ responded:

    We offer a truly cost-effective SEO support for only $129 monthly and shift you up online ranking positions each 30 days or you don't pay. We even business 100 % free SEO in come returning for percentage on web revenue with certain companies. Just contact to see if you are eligible.

  • FNAF World responded:

    Contents like this I can hardly find. Good and full of knowledge.

  • FNAF responded:

    Very efficiently written information.

  • Happy Wheels responded:

    Very useful info, thanks

  • abcya responded:

    let's play abcya games

  • tetris responded:

    let's play tetris games

  • happy wheels responded:

    let's play happy wheels games

  • brain games responded:

    let's play brain games

  • puzzle games responded:

    let's play puzzle games

  • agario responded:

    let's play agario games

  • fnaf 4 responded:

    let's play fnaf 4 games

  • super mario games responded:

    let's play super mario games

  • slither io responded:

    click to play slither io

  • ­wingsio responded:

    click to play wingsio

  • a10 responded:

    I like your all post. You have done really good work.

  • roblox responded:

    I appreciate your working style at the end just my request is please share with us some more great post...

  • color switch responded:

    Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts.

  • mortal kombat x responded:

    Any way I’ll be subscribing to your feed and I hope you post again soon.

  • abcya responded:

    let's click abcya to play for free the best flash games

  • fnaf 4 responded:

    let's click fnaf 4 to play for free

  • slither.io responded:

    let's click slither.io to play slitherio games

  • wings.io responded:

    let's play wings.io game on my sites

  • happy wheels responded:

    let's click happy wheels the game free

  • vertix.io responded:

    I really like the dear information you offer in your articles. I’m able to bookmark your site and show the kids check out up here generally. Im fairly positive theyre likely to be informed a great deal of new stuff here than anyone

  • Dog Games responded:

    Hey what a brilliant post I have come across and believe me I have been searching out for this similar kind of post for past a week and hardly came across this. Thank you very much and will look for more postings from you.

  • Fighting Games responded:

    I think I could probably eat this for dessert! I have never eaten sweet potatoes like this although I have done a similar thing with carrots and loved it.

  • Subway Surfers responded:

    Thanks for sharing.I hope it will be helpful for too many people that are searching for this topic.I must appreciate the way you have expressed your feelings through your blog!. Click here to play

  • Mickey Mouse Games responded:

    Thank you very much for your post, it makes us have more and more discs in our life, So kind for you.I also hope you will make more and more excellent post and let’s more and more talk, thank you very much, dear.

  • slither.io responded:

    let's click slither io to play for free

  • wings.io responded:

    let's play wings io games

  • happy wheels responded:

    let's play happy wheels crazy games on my sites

  • happy wheels the game free responded:

    let's click my name to play for free the happy wheels games

  • abc responded:

    let's play abc games

  • gmail correo electronice responded:

    I Appreciate, Cause I Found Just What I Was Looking For. You've Ended My Four Day Long Hunt! God Bless You Man. Have A Nice Day. Bye

  • Assignment Writing Service responded:

    Great work and indeed this is going to be a lot more exciting.

  • Dissertation help UK responded:

    I will check back in a few minutes. Thanks a million.

  • Nursing essays responded:

    Thanks for sharing such a nice post with us.

  • Prayers For responded:

    I will let you know how well it went.

  • Nursing Schools California responded:

    I second that and it is true.

  • Write my Essays responded:

    Thanks for sharing this post and allow us to publish ours. Want to be part of the blog.

  • tiles richmond responded:

    this is a greatpost. love it...

  • Temple Run 2 responded:

    Very good. you are the winner. Do not forget update new information regularly. thank !

  • fnaf sister location responded:

    Really impressive post. I read it whole and going to share it with my social circules. I enjoyed your article and planning to rewrite it on my own blog.

  • Run 3 responded:

    Oh yeah! They are so adorable~~ Thank you for sharing!! Love these stuff very much >.< With these I think I will start drawing my own

  • Click Jogos responded:

    I like your all post. You have done really good work. Thank you for the information you provide, it helped me a lot. I hope to have many more entries or so from you.

  • juegos gratis responded:

    This blog is so nice to me. I will continue to come here again and again. Visit my link as well. Good luck

  • juegos de futbol responded:

    Great! Thanks for sharing the information. That is very helpful for increasing my knowledge in this field.

  • assignment writing responded:

    Thanks much for this amazing post.

  • dissertation help responded:

    Well done I will do this mock control from up there.

  • Godaddy coupon responded:

    Really great post,thanks for sharing.

  • Hostgator Cloud Web Hosting Review responded:

    I really enjoyed reading your article. I found this as an informative and interesting post, so, I think it is very useful and knowledgeable.

  • pixelgun 3d responded:

    Guys best website with respect to gaming, It has hack for the pixel gun 3d game, and it is delivered for free to
    its users, means now Pixel gun 3d game user can get access to unlimited coins and gems used in this game while playing from the mentioned
    website. Visit to know more about this game and the hack used in this game

  • Sofiya Loani responded:

    Alright looking objectives and uncommon work. Truly flawless data. It has an unrivaled appreciation. a commitment of thankfulness is all together to put imperativeness in it.

  • Riya Sharma responded:

    I believe you may keep up in submitting new substance articles and thank you for sharing your amazing knowledge among us.

  • Vape India responded:


    Evolve Vapors is a USA based company which is operating in Delhi. It is the only company in India that manufactures its own devices as well as flavours. We have two devices an explorer which is meant for smokers to quit smoking and it also ensures a smoker to quit smoking in 48 hours. We also have a device called the brute which is meant for the party animals and hookah lovers. All our products are zero tar, zero tobacco, zero ash and zero smoke free. Nicotine is provided to the people who require it, such as the smokers.

  • webtechcoupons responded:

    It was truly aweosme article i really like this thank you.

  • Amit bhatt responded:

    I really like your post.Thanks for sharing.

  • beyonce responded:

    Thank you for another essential article.

  • Devika Mahajan responded:

    it is a very nice article

  • Hostgator Promo Codes responded:

    That was an awesome one and i would like to share it too.

  • Devika Mahajan responded:

    aayush vaishnve
    mohit vyas

  • Devika Mahajan responded:

    Nice Article

  • Kicks USA deals responded:

    Thanks for sharing this impressive post to us.

  • Nita Shukla responded:

    Great Article

  • hapy wheels responded:

    Enjoy Free Happy wheels game

  • cool math games run 3 responded:

    Thanks for sharing. I hope it will be helpful for too many people that are searching for this topic.

  • LorexTechnology coupon codes responded:

    Your blog is really nice and unique.I like it so much. Looking forward to going over your web page again.

  • Database Tables ColdFusion Project Help responded:

    This is really great work. Thank you for sharing such a useful information here in the blog.

  • java assignments responded:

    My friend recommended this blog and he was totally right keep up the good work

  • SURGICAL PROCEDURE Homework Help responded:

    I appreciate this work amazing post for us I like it.

  • Php Help Center responded:

    John arnold is an academic writer of the Dissertation-Guidance. Who writes quality academic papers for students to help them in accomplishing their goals.

  • Cara menyembuhkan radang telinga responded:

    Thank you so much admin has given information very interesting and helpful to us all and pardon me permission to share articles herein may be useful for all of you in particular who are looking for

  • fb login responded:

    Thanks for your post! it contains quite a lot of things to learn! it's great that I known this site!

  • abc ya responded:

    Thank your site! Can you sharing some updates on how you have made this powerful post!

  • cool math games run 3 responded:


    wow its good one to see this kind of information.

  • Nesa Sugia responded:

    Your website is very interesting and nice, I was very impressed with you. The website that you manage a lot of visitors.Your health may give always. Thank you for sharing and I hope this website you manage to be the best

  • Obat Paru Paru Basah responded:

    Your article is very original, I was amazed by you. It contained interesting to see and not boring. I hope this website you manage to be the best and be number one

  • cool math games responded:

    wow its good one to see this kind of information.

  • cara pemesanan slimming capsule responded:

    http://www.gamatasli.com/keseh...een-world/

  • cara mengatasi pengentalan darah responded:

    http://www.gamatasli.com/keseh...lan-darah/

  • cordyceps plus capsule responded:

    http://www.gamatasli.com/obat-...s-capsule/

  • calcium softgel responded:

    http://www.gamatasli.com/obat-...een-world/

  • cara cepat hamil responded:

    http://www.gamatasli.com/keseh...bat-kimia/

  • obat pembekuan darah di kaki responded:

    http://www.gamatasli.com/obat-...h-di-kaki/

  • Cara menyembuhkan mata perih sebelah responded:

    Thank you so much admin is already providing the information and pardon me permission to share your article may be useful to all, especially the search for the article

  • Obat Penurun Asam Lambung responded:

    I read your complete survey. It's really great & amazing presentation. Thanks a lot for providing this marvelous information which i need so much obat penurun asam lambung

  • jual rumah di pontianak responded:

    Your website is very interesting and nice, I was very impressed with you. The website that you manage a lot of visitors.Your health may give always. Thank you for sharing and I hope this website you manage to be the best

  • Obat tradisional kanker ovarium responded:

    Thank u so much admin and sorry permission share in here :)

  • Obat Asam Lambung responded:

    Exploring a better world for providing this marvelous information which i need to know more. Therefore I think there is no harm if we change the unhealthy lifestyle that we've run with a healthy lifestyle. Thanks

  • slither io responded:

    Thank you for sharing! Can you sharing some updates on how you have made this powerful post!

  • HND Assignment help responded:

    thank you so much

  • Obat Asam Lambung responded:

    Useful information. Lucky me I discovered your website accidentally, and I am stunned why this twist of fate did not happened in advance! I bookmarked it.

  • HND Assignment help responded:

    Thanks for nice post

  • Obat ginjal mengecil responded:

    articles that you provide a very interesting and very useful for my admin and pardon me permission to share articles herein may be useful and helpful

  • Assignment help Australia responded:

    thanks for the post

  • read here responded:

    Good work you done. This is why I feel I can relate to this post very much.

  • aborsi responded:

    awesome share

  • jual obat aborsi responded:

    Good work you done. This is why I feel I can relate to this post very much.

  • Escortsinbangalore responded:

    he blog does not have the full info as I had visited a few other sites to see who had the most complete details. Good effort though

  • thejacketzone responded:

    Great post on the new update that is in the works. Always impressive, always on point! Thanks

  • Dwarkacallgirls responded:

    My very own truthful apologies for not saying because of sooner.

  • Obat Tipes responded:

    Nice post! I really understand the topic, so much insightful and clarity seemed here. Superb sharing

  • Obat Asam Lambung responded:

    I was looking for any article for my school homework and finally got it from you. Thanks.

  • obat polip lambung tradisional responded:

    Highly qualified information because it can provide useful info thanks.
    obat polip lambung tradisional

  • Obat Kanker Usus responded:

    Its really amazing blog with very much helpful information, thank you so much for writing this great blog here for us.

  • Obat Benjolan di Kepala responded:

    Website that you create really really nice and very interesting to see in. I am very happy to be visiting here

  • Obat Gangguan Pencernaan untuk Anak responded:

    The article is very interesting to see, thank you for sharing this very interesting information http://blogpengobatanalamiherb...-anak.html

  • Pengobatan Tradisional Rematik responded:

    Thanks for sharing information very interesting and useful. Do not forget to visit our website to share information and knowledge about health

  • Obat Patah Tulang Paha responded:

    Previously we ask for permission to share, perhaps from you no trouble finding herbal medicinal agent QNC Jelly Gamat. This is the official agent QNC Jelly Gamat are ready to serve the order and delivery. thank you

  • Obat Radang Sendi Lutut Paling Ampuh responded:

    Thanks for sharing the information...Success for the website, as well as the previously asked permission to visit here ...

  • Obat Penyakit Kencing Manis responded:

    The information is very useful and interesting. Thanks for sharing and do not forget to visit our website to share information and knowledge

  • phd dissertation writing services responded:

    This content is written very well. Your use of formatting when making your points makes your observations very clear and easy to understand. Thank you.

  • obat darah tinggi yang ampuh responded:

    a given article is very interesting and very useful for me, thank you very much admin and pardon me permission to share the article here

  • iogames4u responded:

    thank you so much for this

  • usps tracking responded:

    Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.

  • window movie maker responded:

    Thanks for your page! Your share information it helped me alot! I pray for you to be happy and successful in your life.

  • bloxorz responded:

    Interesting article! Thank you for sharing them! I hope you will continue to have similar posts to share with everyone! I believe a lot of people will be surprised to read this article!

  • erp solutions chennai responded:

    I like to seeing this helpful post.Thanks for your information! Keep sharing..
    erp in chennai | erp providers chennai

  • cara mencegah dan mengatasi serangan penyakit jantung pada usia muda responded:

    Highly qualified information because it can provide useful info thanks.

  • windows movie maker responded:

    Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.

Add your own comment...


busy
 
< Prev   Next >

Tweets

    Twitter Button from twitbuttons.com