java


Mockito + Spy: How to gather return values


I got a class using a factory for creating some object.
In my unit test I would like to access the return value of the factory.
Since the factory is directly passed to the class and no getter for the created object is provided I need to intercept returning the object from the factory.
RealFactory factory = new RealFactory();
RealFactory spy = spy(factory);
TestedClass testedClass = new TestedClass(factory);
// At this point I would like to get a reference to the object created
// and returned by the factory.
Is there a possibility to access the return value of the factory? Probably using the spy?
The only way I can see is to mock the factory create method...
Regards
The standard mocking approach would be to:
Pre-create the object you want the factory to return in the test case
Create a mock (or spy) of the factory
Prescribe the mock factory to return your pre-created object.
If you really want to have the RealFactory create the object on the fly, you can subclass it and override the factory method to call super.create(...), then save the reference to a field accessible by the test class, and then return the created object.
First thing, you should be passing spy in as the constructor argument.
That aside, here's how you could do it.
public class ResultCaptor<T> implements Answer {
private T result = null;
public T getResult() {
return result;
}
#Override
public T answer(InvocationOnMock invocationOnMock) throws Throwable {
result = (T) invocationOnMock.callRealMethod();
return result;
}
}
Intended usage:
RealFactory factory = new RealFactory();
RealFactory spy = spy(factory);
TestedClass testedClass = new TestedClass(spy);
// At this point I would like to get a reference to the object created
// and returned by the factory.
// let's capture the return values from spy.create()
ResultCaptor<RealThing> resultCaptor = new ResultCaptor<>();
doAnswer(resultCaptor).when(spy).create();
// do something that will trigger a call to the factory
testedClass.doSomething();
// validate the return object
assertThat(resultCaptor.getResult())
.isNotNull()
.isInstanceOf(RealThing.class);

Related Links

Creating a process from within an instance of Jetty that was launched from Maven
Get the table name from the model in Hibernate
How can I change the color of a particular element of a HTMLDocument in a JEditorPane?
How can I select the local interface for an EJB?
What are the minimum security precautions to put in place for a startup?
Resizing TYPE_CUSTOM BufferedImages?
Timing out tests in TestNG
Proper synchronization of Java threads using wait/notifyAll?
How can I read other parameters in a multipart form with Apache Commons
Representing overloaded methods in UML
How to use connection pool with java,MySQL and Tomcat 6
Parsing XML with REGEX in Java
Which one is better for schema to code generation, XMLBeans or JAXB?
Access JSTL tag from code inside of forEach loop
How to create custom JVM? [closed]
Return a nested class type in Java

Categories

HOME
pdf
listview
debugging
openstack
mfc
path-finding
electron
grep
alfresco
elm
sharepoint-designer
google-project-tango
wamp
flyway4
upload
autotools
communication
wheelnav.js
flask-wtforms
jsprit
netflix
windows-7-x64
finite-automata
aurigma
jqwidget
samoa
google-cloud-speech
firefox-webextensions
zapier
tapestry
chromium-embedded
restful-authentication
dynamic-featured-image
web-api-testing
wtx
large-file-upload
functor
http-referer
atl
google-api-nodejs-client
mmenu
wixsharp
disassembling
swisscomdev
event-driven
starteam
theano.scan
particles.js
gzipstream
sql-server-agent
powershell-dsc
jvm-languages
btrace
youcompleteme
revapi
tizen-native-app
feeds
font-size
r-forge
zendesk-app
nbconvert
jspdf-autotable
django-scheduler
root-framework
nested-sets
time-and-attendance
ado.net-entity-data-model
lua-5.1
testng-dataprovider
whois
bgp
hexdump
associative-array
iad
execute
embedded-code
python-green
xc16
knuth
applescript-objc
wordpress-theme-customize
preferences
neolane
flask-cors
yorick
htmlcleaner
hippomocks
jboss-weld
resty-gwt
jsctypes
jmapviewer
eclipse-memory-analyzer
pushbackinputstream
jquery-knob
unc
word-processor
armcc
newtonscript
jspinclude
regsvr32
reddot
asyncfileupload
gnu-prolog
celltable
xfbml
web-application-design
modelstate
mirah
vc90
ext3
meego
compiler-specific
ti-dsp
swing-app-framework
genealogy

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App