jueves, julio 26, 2012

Answering with Mockito




Overwhelmed by industry, Searching for a modern day savior from another place, Inclined toward charity (The Answer - Bad Religion)

When you are writing unit tests, you must keep in mind to not have dependencies to external components. To avoid this we use mock frameworks which for me the easiest one to use is Mockito.

In this post we are going to see an "advanced" technique used in Mockito to return same argument instance on a mocked method using Answer interface.

Suppose we are writing unit tests for class which manages Person and Job classes and as operation it uses a DAO class for inserting the relationship class (M:N) between Person and Job called PersonJob.

For example class under test will look something like:


So in this case it seems obvious that you need to mock personJobDao.

Let's create the mock and record the interaction:


Yes as you can see you don't know what to return, because instance is created by class under test and in the test method you don't know which instance is created by createPersonJob method. To solve this problem, you need to use thenAnswer instead of thenReturn method:

Note that Answer interface requires you to implement answer method, which in our case simply returns the first argument (PersonJob instance) of personJobDao.create method.

Now we can write assertions in peace without worrying about returned instance.

Hope you have found this post useful.

We keep learning
Alex.

Download Code
Music: http://www.youtube.com/watch?v=S2a3q0nIsoM

39 comentarios:

Anónimo dijo...

I wonder where is the real issue... Isn't it because createPersonJob method does too much, i.e. it knows about how to create a PersonJob object? If you introduce a factory like this:
PersonJob personJob = personJobFactory.create(person, job);
return this.personJobDao.create(personJob);
then this code is very simple to test.

--
Regards
Tomek Kaczanowski
http://practicalunittesting.com

Unknown dijo...

First of all thank you very much for reading my blog, well I agree with you that the solution you provided will make code simple to test, you would only need to mock personJobFactory and personJobDao. You can decide to create a factory for all your classes that requires a M:N relationship, this is good, but you can also follow Persistence Manager pattern which is the responsible (as shown in this post) of managing M:N relationships without a factory.

Regards,
Alex.

Tomasz Nurkiewicz dijo...

If you are forced to use Answers in Mockito, at least wrap them in well named, static methods available somewhere. You must agree this is much more readable:

when(personJobDao.create(any(PersonJob.class))).thenAnswer(withFirstArgument());

Unknown dijo...

Hi Tomasz I totally agree with you, in face I usually use this approach or for example when using Converter interface of Lambdaj project I use the same approach you pointed here, but I try to give a very simple example so it is compact, reader will not require to jump over functions to know how they are implemented. But of course in production code I will do what you commented in your comment.

Thank you very much for reading my blog.

Alex.

yanmaneee dijo...

moncler
kd 11 shoes
golden goose
adidas tubular
jordan store
golden goose sneakers
balenciaga sneakers
air max 97
michael kors outlet store
kobe shoes

Alex Smith dijo...

Hard to ignore such an amazing article like this. You really amazed me with your writing talent. Thank for you shared again.
Norton setup - Get started with Norton by downloading the setup and installing it on the device. Enter the unique 25-character alphanumeric product key for activation. Check your subscription norton.com/setup | norton.com/setup | norton.com/setup

Alex Smith dijo...

Thank you so much for sharing such a superb information's with us. Your website is very cool. we are impressed by the details that you have on your site.we Bookmarked this website. keep it up and again thanks
Login or sign up at office setup and download Microsoft Office. Install and activate the setup on your device. Verify the Office product key office.com/setup | norton.com/nu16

Alex Smith dijo...

Hard to ignore such an amazing article like this. You really amazed me with your writing talent. Thank for you shared again.
Norton setup - Get started with Norton by downloading the setup and installing it on the device. Enter the unique 25-character alphanumeric product key for activation. Check your subscription norton.com/setup | norton.com/setup | norton.com/setup

avawilliams1122 dijo...

office.com/setup microsoft office has thought of an assortment of new invigorates in its applications, for instance, word, surpass desires, powerpoint, access, and others. these new updates features are open to all microsoft customers from home to business to class use. this generally commended
office.com/setup

office.com/setup

mcafee.com/activate

mcafee.com/activate

mcafee.com/activate

mcafee.com/activate

Alex Smith dijo...

Thank you so much for sharing such superb information's with us. Download the Microsoft Office setup on your Windows or Mac computer. Make sure that the Office product key is already copied for the activation procedure. office.com/setup mcafee.com/activate|office.com/setup

Alex Smith dijo...

Activating McAfee is a quick and simple process. You just need to copy your 25 characters alphanumeric product key and paste it in the activation tab. Let’s check out the step-by-step process #mcafee #activate
mcafee.com/activate | mcafee.com/activate | mcafee.com/activate | mcafee.com/activate

mcafee.com/activate dijo...

I am very thankfull to you for sharing this fantastic article , I appereciate your work .

mcafee.com/activate , mcafee.com/activate , mcafee.com/activate

Anónimo dijo...

Norton is one of the top most antivirus for computers and gadgets, to download and setup Norton antivirus you need to visit Norton.com/setup or www.norton.com/setup. In this article we will guide you all steps which are necessary to activate Norton antivirus on windows.

Nora Miller dijo...


Visit www.mcafee.com/activate for download and activate your mcafee product, and if you have any issues you can directly call at mcafee toll free number.

mcafee activation key support
activation key for mcafee
mcafee activation
how to activate mcafee
mcafee product activation
how to activate mcafee
mcafee com setup activation
mcafee antivirus code
mcafee activation support
mcafee activation code
mcafee activation key


i-nortonnorton dijo...

If you face any trouble at www.norton.com/setup in the course of redeeming Product key, down load and installing norton setup, Please call us toll-free USA/CANADA: +1-855-619-5888
Australia: +61-800-941-031
UK: +44-800-041-8972

Unknown dijo...

eset internet security can be installed quickly on each device if the user follows the correct procedure. You can follow the instructions below to install the setup on your devices such as Windows PC, Mac, or mobile device. Best IT security solutions for your home and business devices. Try ESET antivirus and internet security solutions for Windows, Android, Mac or Linux OS.

sigmamarry dijo...

McAfee Antivirus additionally squares malware that incorporates noxious sites, rootkits, Trojans, infections, and phishing plans. It gives you in-program reports about the dangers it squares. McAfee Antivirus records the IP tends to associated with the danger, which permits technically knowledgeable clients to maintain a strategic distance from sites associated with those addresses.
mcafee.com/activate | mcafee login | install mcafee with activation code

sigmamarry dijo...

mcafee.com/activate as antivirus of virus furnishes you with the security shields to prevent malicious documents from entering in the Desktop, PC/cell phone by means of malware, spyware, rootkit, and Trojan ponies. As individuals all around the globe complete their regular work on their official and PCs, they require absolute protection from a wide range of dangers that these infection records can cause. These infections are produced abruptly from old PC-stuck records or dubious Trojan pony, spyware, and malware online sites.
mcafee.com/activate | www.mcafee.com/activate | mcafee download | mcafee activate

Malware bytes dijo...

Are you facing the problem of Malwarebytes install error? If you are seeing this error message upon the start of your computer, it is clear that you have not installed the program correctly. There is no need to worry though as we can fix this error easily for you.

AlexaMartin dijo...

I almost spent an hour on your blog reading several of your posts. I got clear idea of certain of my doubts. I really appreciate the posts you have shared. Keep sharing more!

office.com/setup

Lillian J. Turner dijo...

Nice Blog. Thanks for sharing with us. Such amazing information.

MyBlogger Club

Guest Posting Site

Best Guest Blogging Site

Guest Blogger

Guest Blogging Site

Janny kayle dijo...

Are you getting errors when you try to activate your Microsoft office activation subscription? Then read on to get step by step guide to solve Microsoft office activation errors. Install, and activate your Office setup on your computer and other devices.
office.com/setup
www.office.com/setup
office.com/setup
www.office.com/setup

qwe dijo...

vestito stile smoking bianco
chaussure de basketball nike zoom kobe 12 femme
abrigos de pelo mujer lefties
nike air max blancas mujer baratas
panini fußball sticker 2016 amazon
nike air jordan sale deutschland
hoodie pepe jeans cyan
zapatillas bimba y lola outlet
chaqueta adidas trefoil delantero
Supeme Hoodie
sandalia rafaela melo
kimono long femme grande taille
skechers twinkle toes light up boots
chanel hosenträger kaufen
maillot de bain push up pour homme
shirt mit schnürung am ausschnitt
vestito da elsa disney
tabouret de bar vintage cuir
moleton nike preço
zalando nike zoom fly
carrinho com bebe conforto travel system

Mark Watson dijo...

On your Mac, go to Applications > Utilities, then select the Keychain Access app. Select the Password menu located on the left side. Simply type the word “base station” on the search bar. Click the base station keychain. Go to the attributes option. Simply select the Show airport extreme default password Button.

Unknown dijo...

The Webroot program is highly rated software to protect your devices & data available for download at
ij.start.canon| ij.start.cannon/ts3322 | Microsoft365.com/setup
| microsoft365.com/setup | www.hp.com/go/wirelessprinting

Unknown dijo...

A Quick Guide to Canon Printer Setup
Make sure your printer hardware is configured.
On your PC browser, go to canon.com/ijsetup.
Click Set Up.
Using your Canon IJ printer model, the download printer software.
Double click to install it.
Connect a network to your printer and PC.
Finish the Canon IJ printer setup.
LaserJet Printer Setup
Configure your HP Printer hardware. Visit 123.hp.com/laserjet from the browser. Using your LaserJet model name, download software. Double click to start the installation. Connect the printer via wireless network or USB. Add the LaserJet printer to your system devices.Finish the HP LaserJet setup.

james Smith dijo...
Este comentario ha sido eliminado por el autor.
Unknown dijo...

A Quick Guide to Canon Printer SetupMake sure your printer hardware is configured.
On your PC browser, go to cannon.com/ijsetup
Click Set Up.
Using your Canon IJ printer model, the download printer software.
Double click to install it.
Connect a network to your printer and PC.
Finish the Canon IJ printer setup.
HP LaserJet Printer Setup
Configure your HP Printer hardware.
Visit 123.hp.com/leserjet t from the browser.
Using your LaserJet model name, download software.
Double click to start the installation.
Connect the printer via wireless network or USB.
Add the LaserJet printer to your system devices.
Finish the HP LaserJet setup.

james Smith dijo...

cannon printers installation step process To begin, download the correct model drivers for the printers. Before downloading and installing it, make sure that the operating system version is compatible and follow the ij start cannon steps.

Unknown dijo...

A new purchased (or older) Canon printer needs to be set up.https://ij.start.cannon | https //ij.start.cannon | http://ij.start.cannon
PIXMA MG2522 all-in-one printer is the best choice for all home printing needs and small businesses as well. First, visit canon.com/ijsetup mg2522 | canon.com/ijsetup/mg2522
Use your Outlook, Skype, Xbox or any other Microsoft account to sign in. To avoid any error during Microsoft 365 installation, follow the instructions mentioned below. microsoft365.com/setup | www.microsoft365.com/setup

amelia dijo...

Defend against the unknown threats and proceed for Trend micro download with www.trendmicro.com/activate having Advanced Machine Learning Technology. Trend micro security is the best way to save your Connected World to all the digital part. Install www.trendmicro/activate from the official site and get the trend micro activation key to complete the process.

Unknown dijo...

A Quick Guide to Canon Printer SetupMake sure your printer hardware is configured.
On your PC browser, go to cannon.com/ijsetup
Click Set Up.
Using your Canon IJ printer model, the download printer software.
Double click to install it.
Connect a network to your printer and PC.
Finish the Canon IJ printer setup.
HP LaserJet Printer Setup
Configure your HP Printer hardware.
Visit 123.hp.com/laserjet from the browser.Using your LaserJet model name, download software.Double click to start the installation.Connect the printer via wireless network or USB.Add the LaserJet printer to your system devices.Finish the HP LaserJet setup.

EZWorks dijo...

Animated whiteboard films may be an excellent alternative if you want to tell your message in an engaging and entertaining way. Whiteboard animation videos stand out as a means of communicating your message since they are simple, yet friendly and powerful. The numerous advantages of whiteboard films demonstrate that this format may be an effective marketing tool for your company or business. Get in touch with the best audio visual experts at EZ to get amazing whiteboard videos made!

Kaylee Brown dijo...

In a class, when the subject is pretty hard, the professor finds time to explain to everyone present. But if the topic seems easier, and an individual student faces problems handling the topic, the teacher will not always help. Students sometimes feel shy to ask for such explanations. This, in turn, harms the career of the student. The student needs to learn the topic, and at the same time, he needs to finish the assignment too! Hence, the student goes for java assignment help and spends the time learning the subject by heart. When the professors cannot explain the portions individually, the students need to take help from online teaching platforms or from the assignment service providers to understand a certain topic!

John Ruth dijo...

Wow...Nice Post. I'm Really Appreciate your written skills.

hp officejet pro 8600 driver | www.hp.com/go/wirelessprintingsolutions.brother.com/windows | 123.hp.com/laserjet | 123.hp.com/laserjet

John Ruth dijo...

ij.start.canon ts3122 | ij.start.canon | Microsoft365.com/setup/familyMicrosoft365.com/setup/personal | Microsoft365.com/setup/business

stesyveau dijo...

replica bags replica gucci bags f3n72v6n34 replica bags hermes try this x9g86t9b88 7a replica bags wholesale replica goyard bags replica chanel bags ebay blog link g9i51l8z82 replica bags in pakistan

Hostdocket dijo...

QuickBooks is one of the best accounting software available in the market. Designed to cater both medium and small businesses, this software has changed the way accounting, payroll and bookkeeping is done. lost QuickBooks product and license number as it’s, packed with powerful features, today more and more companies using it. However, it is a software and that’s why often face technical errors. But all these errors can be easily handled as many articles available in the internet.

Hostdocket dijo...

Learn about QuickBooks error code h202
Usually when working on QuickBooks, one might land into some or the other QuickBooks error. The reason behind these errors can be the code and algorithm involved in this software. However, one of the best things about QuickBooks is the fact that all the errors can be easily rectified using some set