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

How to know the file size when uploading via multipart form-data?
Problem while copying WidgetCollection in GWT?
Java collision detection for rotated rectangles?
Java: set timeout on a certain block of code?
how to minimize & maximize table in jsp
Convert ascii to int? [duplicate]
Validate an emailAddressfield in blackberry
Findbugs SIO_SUPERFLUOUS_INSTANCEOF
Java implicit “this” parameter in method?
Open a new prompt/terminal window from Java
What is the right way to handle NaN in Java?
How to create a simple state machine in java
Does axis 2 support REST?
Is it possible to have an Eclipse project w/ one package that executes as a Android app, and a second package that executes as a Java SE app?
textarea composite widget
Better way to check if a joda.time.Interval spans exactly 1 calendar week (accounting for daylight savings etc)

Categories

HOME
compiler-construction
vim
microservices
frameworks
gps
blueprintjs
azure-media-services
append
contact
primary-key
metatrader4
decimal
pythonanywhere
nas
abi
jquery-ajaxq
excel-2007
format-specifiers
rundeck
one-to-many
dynamic-featured-image
assistant
msys2
skia
catel
pim
stacked
serve
abstract-class
keydown
modelmapper
auto-update
clean-architecture
winscp-net
return-value
fancybox-2
rdfs
gabor-filter
sqldf
redundancy
messenger
pagedlist
prettytensor
essence
php-parse-error
browser-link
jfugue
marching-cubes
deis
sankey-diagram
sonarqube5.1.2
inmobi
directoryservices
javax.mail
geonetwork
csquery
cdt
android-nested-fragment
gulp-less
phpthumb
.aspxauth
runtime.exec
apc
bulkloader
file-locking
batterylevel
eventlistener
selected
e4x
unc
chuck
mt
bluepill
online-compilation
postgresql-performance
punbb
eclipse-templates
psi
nintendo-ds
mtj
pascal-fc
text-coloring
mediarss
defensive-programming

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App