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

54 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

James Boond dijo...

It read your article every thing is clear , Thanks for sharing.

office.com/setup , 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

Mark William dijo...

Trend Micro Internet Security subscription is the single way to download the software on multiple devices through www.trendmicro.com/downloadme . Trend micro has become a superior antivirus program over many antiviruses due to its advanced protection features. trend micro download process becomes easy when you purchase the subscription.

Mark William 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

sigmamarry dijo...

Hey its john,I joned this communities for purpose of promote my technical site.Norton setup is where do you enter the Norton Setup Key at norton.com/setup to enact and introduce Norton item. Norton password generatot tools avoilable on Norton website : Norton setup
norton.com/setup || norton download | norton login | norton.com/setup | Norton setup | norton password generator

sigmamarry dijo...

microsoft office setup is truly outstanding and the greatest of the profitability programming's accessible in the efficiency programming industry. The product business has grown a ton in the 21st century,official website is here for visiting: office.com/setup we have even observed a lot of programming that are presently incorporated with the product that can really give an extraordinary lift to the product business.

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

xingxing dijo...

giacca da prestigiatore
triciclo usato milano
risparmiare batteria iphone ios 12
maglia termica nuoto bambina
shein camicie donna cameriera
maquina para coser zapatillas
venta de bicicletas para ejercicio
sujetador media copa abierto ético
nike academy16 knt tracksuit 2
bañador neopreno mujer oysho
camiseta escote redondo
adidas rock climbing
rompecabezas de obras de arte para arma
reloj con números romanos para niños
abrigo aviador mujer abdomen
gucci forocoches
sonic 3 and knuckles juego online
short de bain islamique
stihl klamotten
brabus rocket 900 amazon
new balance icarus
sonnenbrille herren mit seitenschutz
hoodie pepe jeans cyan
shorts fitness feminino
melhores marcas de mochilas masculinas
quadri da disegnare amazon
aharry potter x vans
culle e passeggini per neonati amazon
camisa da ferroviária
galocha rosa feminina
deichmann bolsos
bolso de mano de hombre guess entusiasta
tenda da sole spiaggia amazon
nike pegasus 94
Nike Air Force 270

diamondsymons2 dijo...

casquette ford Immigration
chaussure carla moreau
triciclo usato milano
chaussures de sécurité facom
foot locker nike react element
scatola protezione stagna
nike metcon 5 rojas
zapatillas de agua niña
veste velour carhartt
damen lack schnürer
cappotto rosso scarpe nike
fiore garofano amazon
nike presto extreme pas cher
nike pegasus 94
shorts fitness feminino
nike t shirt tumblr
quadri da disegnare amazon
chinelo slide da melissa
tenis all star feminino branco couro
calzoncillos puma hombre
veste per battesimo amazon
nike air force modelo agotado
cartera levis hombre
filtre pour aspirateur samsung sc4780
autoradio gps vdo
nike tribute veste
soldes chaussures homme caterpillar hiver cafétéria
amazon sandalias reef
chanclas new balance niña
kit de creation de bracelets utilisation
wc suspendu mural amazon
foulard en soie homme
all star converse star player
paragliding přilby
nike anzug nba rot
camisa da ferroviária
tapie adidas credit lyonnais
gucci handbags uk
air force 1 nike outfit men basket

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

Janny kayle dijo...

Microsoft 365 provides more security than a basic Office 365 subscription, with features such as Enhanced Security Features, wireless cleaning, and app safety and security that prevents duplication.. Instead of using Microsoft Word and Excel, Microsoft 365 offers a range of useful features.
microsoft365.com/setup
office.com/renew
office365.com/setup
microsoft365.com/setup
office.com/renew
office365.com/setup

Janny kayle dijo...

Home and Student 2019 is designed for students and families who choose to use classic Office software such as Excel, Word, and PowerPoint on Windows and Mac. It’s a one-time purchase that can be used at home or in the classroom on one PC or Mac.
office.com/setup home and student 2019
office.com/setup home and business 2019
office.com/setup home and student 2019
office.com/setup home and business 2019

Janny kayle dijo...

Visit our website and Troubleshoot the most commonly occuring errors of Microsoft office by the easiest steps. 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

bedortheadora dijo...

kiabi bottine femme
polo lacoste ton sur ton
pepe jeans tami
crampon vissé adidas
brassiere garcon
vestido de niña rosa palo
maglia termica nuoto bambina
adidas zx flux adv virtue sock w
nike cortez prm
beutel zipper amazon
nike tanjun damen weiß 44
scarpe pirelli uomo impedire
polo ralph lauren jeanshemd damen
risparmiare batteria iphone ios 12
style année 80 femme
Nike Air Force 270
kimono en jean
pantaloni puma femei pollice Linea di metallo
shein camicie donna cameriera
bañador neopreno mujer oysho
sudadera nike vintage
giacca da prestigiatore
sandalias courofeito a mao
grossista condizionatori
piumini daunenstep amazon
zapatillas cruyff mujer
valentine gauthier chaussures
nike huarache og colorways
pull lacoste col montant activer
zirkus jacke herren amazon
maglia as roma blu
tabouret pour toilette amazon
puma calçados femininos desvaneça
adidas duramo 7 precio
nike air force one rot schwarz
vestito stile smoking bianco
chaussure de basketball nike zoom kobe 11 femme
welke scooter moet ik kopen

qwe dijo...

nike air max sandale au sens propre
pull lacoste col montant activer
zirkus jacke herren amazon
maglia as roma blu
tabouret pour toilette amazon
puma calçados femininos desvaneça
adidas duramo 7 precio
nike air force one rot schwarz
vestito stile smoking bianco
chaussure de basketball nike zoom kobe 11 femme
welke scooter moet ik kopen
air max 97 capitao america
polo shirt juventus
sfera vestido flecos mostaza
leggings mit spitzenabschluss
kugelbahn ab 12 monate amazon
nike air max sandale au sens propre
pull lacoste col montant activer
zirkus jacke herren amazon
maglia as roma blu
tabouret pour toilette amazon
puma calçados femininos desvaneça
adidas duramo 8 precio
nike air force one rot schwarz

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.

macfeesactivateis 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

macfeesactivateis dijo...

Visit ij.start.canon | ij.start canon and find out the best way to download Canon printer drivers. Canon printers are ideal for every situation wherever you need a document, paper, or photo print or even if you wish to scan, fax, and do more ijstart.canon will make you learn how to set up a canon printer to get advanced printing features. To complete your Canon ij printer setup with several connectivity options like WiFi, USB, Bluetooth, and others, see and follow below mentioned steps.

macfeesactivateis dijo...

Enter Trend micro activation code on www.trendmciro.com/activate | www.trendmicro/activate to download and activate Trend Micro. To activate Trend micro, make sure you already have an activation code that you’ll probably enter on the trendmicro.com/activate site.

technoblogs 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.

technoblogs dijo...

microsoft365.com/setup allows you to download and activate the Microsoft Office setup. Microsoft 365 plans for personal and home provides robust Office desktop apps including Word, PowerPoint, Excel, Outlook, and OneNote.Microsoft 365 subscribers can always install the latest version of MS Office and get frequent software updates. If you have a Microsoft account, sign in and enter the product key at microsoft365.com/setup to activate your product. Install and set up your Office 365 apps with the given instructions.

Activate setup dijo...

Several factors matter when you choose the Microsoft 365 subscription. Depending on your requirements on the respective productivity platforms, these products are different in price. microsoft365.com/setup

james Smith dijo...
Este comentario ha sido eliminado por el autor.
technoblogs 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.

Microsof365setup dijo...

office setup product key is a secured
25 digit alphanumeric code series xxxxx-xxxxx-xxxxx-xxxxx-xxxxx.
This activation key can be used summarily to install and activate
the product with ease. One can effortlessly access more information
about these product keys at office products today.


Regards

microsoft365.com/setup
microsoft365.com/setup/family
microsoft365.com/setup/personal
microsoft365.com/setup/business
office.com/setup home & student 2019
office.com/setup for home & student 2019

henrynikk07 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...

Canon Pixma MG 2522 is an all-in-one inkjet printer equipped with multifunctional features like printer, scanner, and copier.
Canon.com/ijsetup/mg2522 |
Canon.com/ijsetup mg2522
| camps.intuit.com | camps.intuit.com

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.

technoblogs 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.

Activate setup dijo...

HP LaserJet printer uses the Laser technique to print, scan, and copy documents. 123.hp.com/laserjet | www.trendmciro.com/activate | www.trendmicro/activate | trend micro activation

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!

henrynikk07 dijo...

On the web address bar, enter the https://ij.start.cannon URL and press Enter key. The http://ij.start.cannon is a Canon printer drivers download site that offers the latest software and drivers to download on your operating system. https //ij.start.cannon

If you don’t get any cable to connect MG2522 to your PC or laptop, ensure you purchase a USB 2.0 A/B cable. First, visit canon.com/ijsetup mg2522 | canon.com/ijsetup/mg2522

Unknown dijo...

Visit multiple websites to compare immersion rod prices and buy immersion rod. If you want to buy an immersion rod at less price, contact us. KENSTAR has affordable appliances for your house.
immersion rod

macfeesactivateis dijo...


Visit www.hp.com/go/wirelessprinting and open the door to the world of HP smart printing solutions. HP wireless printer is a versatile printing device that helps you print, scan, copy and fax your documents as per the requirement.
Visit ij.start.canon | ij.start canon and find out the best way to download Canon printer drivers. Canon printers are ideal for every situation wherever you need a document, paper, or photo print or even if you wish to scan, fax, and do more ijstart.canon will make you learn how to set up a canon printer to get advanced printing features.