java


Mocking Java objects in my target where target has no setters available


The situation is that I have to write Unit test for one of Java class. That java class in the constructor creates object of another class(3rd party), no so setter available for setting the 3rd party class.
I do not have the 3rd party class available with me, so would like to mock it. So is it possible by Mockito or any other framework or any other suggestion.
One option I see is to self create that 3rd party class (with same package info) and provide called functions returning whatever I wish and provide class path where these mocked will exist.
You could create a subclass of the 3rd party class from within your unit test class and override the relevant methods.
private class TestClass extends 3rdParty {
public TestClass() {
super();
}
#Override
public String myMethod() {
return "";
}
}
So in your unit test you create the subclass object instead of the 3rd Party one.
TestClass test = new TestClass();
System.out.println(test.myMethod());
You could use a spy to override behavior of the third-party instance.
For example, with Mockito it might look like this:
package org.foo;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.doReturn;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
#RunWith(MockitoJUnitRunner.class)
public class FooTest {
private static class ThirdParty {
public String getName() {
return "Third party implementation";
}
}
#Spy
private ThirdParty toTest = new ThirdParty();
#Test
public void test() {
// Arrange
doReturn("Hello").when(toTest).getName();
// Act
final String name = toTest.getName();
// Assert
assertEquals("Hello", name);
}
}
Or you can use a standard mock if you don't actually require any of the third-party behavior:
#Mock
private ThirdParty toTest;
#Test
public void test() {
// Arrange
doReturn("Hello").when(toTest).getName();
// Act
final String name = toTest.getName();
// Assert
assertEquals("Hello", name);
}
You could overload your constructor so you can pass in your mocked version of the ThirdPartyClass:
public class MyClass {
private ThirdPartyClass thirdPartyObject;
public MyClass() {
this.thirdPartyObject = new ThirdPartyClass();
}
public MyClass(ThirdPartyClass thirdPartyObject) {
this.thirdPartyObject = thirdPartyObject;
}
}
public class MyClassTest {
#Test
public void someTest() {
ThirdPartyClass thirdPartyObject = Mockito.mock(ThirdPartyClass.class);
MyClass underTest = new MyClass(thirdPartyObject);
...
}
}
I like JMockit for this (and mocking generally).
import mockit.Mocked;
import mockit.NonStrictExpectations;
...
public class SubjectTest {
...
#Mocked ThirdPartyClass thirdPartyObject;
...
#Test
public void should_do_whatever() {
// arrange
new NonStrictExpectations() {{
thirdPartyObject.someMethod(); result = <your desired output>;
}};
// act
...
// assert
...
}
}
Just to ensure this thread is closed, I ultimately used PowerMock.
It helped me to mock behavior of private functions and static functions of other classes/objects that were used by the Test candidate object.

Related Links

String concatenation: concat() vs “+” operator
Practical Experience using Stripes?
JUnit for database code
Can a java fixedThreadPool be used by multiple threads
How to generate running time graph for my Java program
Shortest way to get an Iterator over a range of Integers in Java
Java listener must inherit from java.util.EventListener - why?
How to synchronize requests for data with data update process?
Error connecting to oracle. Getting an UnsatisfiedLinkError for the method t2cGetCharSet
Upgrade to Quartz 1.6 on JBoss 4.2.x
How to mock the InitialContext class with jmockit?
Java: Are concurrent reads and writes possible on a blocking SocketChannel via Object(In|Out)putStreams?
Is there a more elegant way to convert an XML Document to a String in Java than this code?
Conditional Number Formatting In Java
How to write java.util.Properties to XML with sorted keys?
How would I allow a user to stream video to a web application for storage?

Categories

HOME
coq
c#-4.0
mfc
dot
react-router
alfresco
android-4.4-kitkat
react-redux
analysis
amazon-ecs
rdf
windows-server
ezpublish
yum
fancybox
podio
cross-validation
contact
facebook-messenger-bot
facebook-php-sdk
collectd
remote-access
clearcase-ucm
oracle-coherence
beyondcompare
scichart
predix
autoconf
cloudhub
accessor
chromium-embedded
emgucv
one-to-many
fish
nhapi
windows-error-reporting
facebook-apps
atlassian-crucible
copying
avcapturesession
geopositioning
nssegmentedcontrol
bower-install
revolution-slider
main
retina-display
dynamics-crm-2013
starteam
sharefile
twitch
trim
pdf-reactor
isbn
arena-simulation
reactive-cocoa-5
.net-4.6.2
google-datalayer
apache-fop
paxos
pebble-watch
dotnetzip
brightcove
mcafee
django-scheduler
google-cdn
root-framework
login-control
superstack
sdf
bluegiga
wapiti
uid
cyclomatic-complexity
django-unittest
sframe
unity5.2.3
p2
bridge.net
block-device
terminfo
bundles
balanced-payments
java.nio.file
mcts
google-cloud-save
eclipse-memory-analyzer
enterprisedb
isnullorempty
multipage
hgsubversion
deobfuscation
gcj
invite
datareader
gamma
filtered-index
preference
uimenucontroller
avatar
.net-1.0
paul-graham

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