unspoken reflections of my heart
technology
A dive into Mockito – Part 2
Jun 11th

Part 2 – Argument Matchers and Stubbing Void Methods
- Using Argument Matchers
- A simple use of any() matcher
- Writing Custom Argument Matchers
- Stubbing void methods
Using Argument Matchers
Mockito argument matchers can be used to specify the method arguments for stubbing. If the method has arguments but you really don’t care what gets passed or cannot predict it, argument matchers can be used.
Argument Matchers provide us a lot of flexibility in stubbing.
Argument Matchers use the equals() method for comparisons.
A simple use of any() matcher
Let us assume we have an EmailService that is trying to save an email ID using an EmailManager. This means that the save() method of the EmailService calls the save() method of the EmailManager, which in turn saves the email to the database. A simple unit test for the save() method of the EmailService can test whether the save() on the Manager was called.
import org.junit.Test;
import org.mockito.Mockito;
public class EmailServiceTest {
@Test
public void testSaveEmail() {
EmailManager manager = Mockito.mock(EmailManager.class);
EmailService service = new EmailService(manager);
service.save("abc@xyz.com");
Mockito.verify(manager).save(Mockito.anyString());
}
}
Note the use of the argument matcher in line 12:
Mockito.verify(manager).save(Mockito.anyString());
We used the matcher because, we really do not care what parameter was passed on the save().
The generic any() matcher:
Mockito provides a matcher that matches any Object. Some valid variants of the above are:
Mockito.verify(manager).save(Mockito.any()); Mockito.verify(manager).save(Mockito.any(String.class));
The cast from Object to String is required in the first line, the lack of which will cause compilation error.
The second line shown above is most useful when we need to match custom classes we create in our application.
Assuming save() method saves a Person object, we would write:
Mockito.verify(manager).save(Mockito.any(Person.class));
While using argument matchers in stubbing, all arguments of a method must be matchers.
If our save method also takes in an integer, this line would throw error:
Mockito.verify(manager).save(12, Mockito.any(Person.class));
To fix the above scenario, we can write:
Mockito.verify(manager).save(Mockito.eq(12), Mockito.any(Person.class));
Some common Argument Matchers
| ARGUMENT MATCHERS | DESCRIPTION | |
|---|---|---|
| any() or any(Class | Any object (or object of a given class) or null | |
| anyString() anyInt() anyFloat() anyDouble() anyBoolean() anyByte() anyChar() | anyObject() anyCollection() anyList() anyMap() anySet() | Any object of given type or null |
| eq | Default Matcher. Compares using equals() method | |
| same | Object argument that is the same as the given value. Compares using == | |
| refEq | Object argument that is reflection-equal to the given value. This Matcher can be used when equals() is not implemented on compared objects. Matcher uses Java reflection API to compare fields of wanted and actual objects. | |
| isNull isNotNull | Argument is null/not null | |
| contains(String substring) matches(String regex) endsWith(String suffix) startsWith(String prefix) | String-specific argument matchers | |
Writing Custom Argument Matchers
Consider this scenario. We have the following classes:
- Person – A class with two variables – name, email id
- PersonService – A service class that creates a Person object and calls savePerson() method on the manager
- PersonManager – The manager class that needs to be mocked
We need to write test case for personLogic() method in PersonService
PersonService.java:
public class PersonService {
private final PersonManager manager;
public PersonService(PersonManager manager) {
this.manager = manager;
}
public void personLogic() {
Person person = new Person("Karthik", "abc@xyz.com");
manager.savePerson(person);
}
}
The below test will fail:
import org.junit.Test;
import org.mockito.Mockito;
public class PersonServiceTest {
@Test
public void testPersonLogic() {
PersonManager manager = Mockito.mock(PersonManager.class);
PersonService service = new PersonService(manager);
service.personLogic();
Person verifyPerson = new Person("Karthik", "abc@xyz.com");
Mockito.verify(manager).savePerson(verifyPerson);
}
}
Reason: The expected object, with reference verifyPerson is entirely different from the actual object, and the default equals() comparison which argument matchers use, fails.
Use Custom Argument Matcher
In this scenario, using custom argument matchers come in handy.
Lines 12 and 13 above can be replaced with this:
Mockito.verify(manager).savePerson(
Mockito.argThat(new ArgumentMatcher() {
@Override
public boolean matches(Object argument) {
Person person = (Person) argument;
return person.getName().equals("Karthik")
&& person.getEmail().equals("abc@xyz.com") ? true
: false;
}
}));
Alternate Solution – 1
Use the refEq matcher to compare the fields of the objects in hand:
Person verifyPerson = new Person("Karthik", "abc@xyz.com");
Mockito.verify(manager).savePerson(Mockito.refEq(verifyPerson));
Alternate Solution – 2
Override the equals() method in Person class to compare objects.
Stubbing void methods
We face a lot of scenarios in our applications where we need to stub void methods. With void methods, stubbing is slightly different. We cannot use void methods in the when() call.
The alternative syntax is:
Mockito.doReturn(result).when(mock).method();
We can also test exception handling. How would my code handle if an exception is thrown by void methods
Mockito.doThrow(new RuntimeException()).when(mock).setAttribute(Mockito.anyString());
We can also set the behaviour of a void method to do nothing when called. This is not possible for non-void methods:
Mockito.doNothing().when(mock).method();
Why when() does not work for void methods:
Take a look at the syntax of when():
when(mock.method())
Notice that the method is called inside brackets. Compiler does not like void method inside brackets!!
The two ‘when()’ are different syntax.
Notice that the when() for a non-void method stubbing takes in a methodCall as parameter, whereas the when() in void method stubbing takes in a mock object.
| STUBBING WITH MOCKITO | USAGE |
|---|---|
| do | Primarily used for stubbing void methods |
| doCallRealMethod().when(mock).method(); doNothing().when(mock).method(); doThrow(Throwable... throwables).when(mock).method(); doReturn(T value).when(mock).method(); doAnswer(Answer> answer).when(mock).method(); |
|
Future articles in the series:
- Part 3 – Partial Mocks using Mockito and Limitations of Mockito
A dive into Mockito – Part 1
May 31st
Part 1 – Getting Started with Mockito
- Mocking Frameworks – Mockito
- A simple use of Mockito
- Verifying Interactions with the mock
- Stubbing methods using when()
Mocking Frameworks
Mocking Frameworks allow us to test the code you want, without its dependencies. In a unit test, mock objects can simulate the behaviour of complex objects that are impractical or impossible to incorporate into a unit test.
Mock objects isolate the unit of code you are testing.
Mockito
This is a framework used for test stubbing and interaction testing.
Let us assume that we have a simple servlet, and a method testCheckFormat() that checks the format of the email id submitted in the HTML form. It is impractical to create an actual HttpServletRequest object for unit test. So we mock this object, in order to test the code we are interested in.
A simple use of Mockito
import javax.servlet.http.HttpServletRequest;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
public class ServletFacadeTest {
@Test
public void testCheckFormat() {
HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class);
Mockito.when(requestMock.getAttribute("email")).thenReturn("xyz@abc.com");
ServletFacade servletFacade = new ServletFacade();
boolean result = servletFacade.checkFormat(requestMock);
Assert.assertEquals(true, result);
}
}
There are three fundamental steps in writing JUnit test cases with Mockito:
- Create a mock of the object on which the method under test is dependent [line 10]
- Specify behaviors on the mock object (stub) [line 11]
- Assert/verify test scenario [lines 14-16]
Verifying Interactions with the mock
One of the most important capabilities of Mockito is to verify whether the mock had any interactions. A mock object will remember all its invocations.
The following test would have passed in the above case:
Mockito.verify(requestMock).getAttribute("email");
It is also easy to ensure that there were no more interactions with our mock apart from getting the email:
Mockito.verify(requestMock).getAttribute("email");
Mockito.verifyNoMoreInteractions(requestMock);
Let’s assume that our logic now tries retrieving two details from the request, namely email and name. To test two invocations, we now can use:
Mockito.verify(requestMock).getAttribute("email");
Mockito.verify(requestMock).getAttribute("name");
We can write this slightly differently, using argument matchers provided by Mockito:
Mockito.verify(requestMock, Mockito.times(2)).getAttribute(Mockito.anyString());
Verifying a stubbed invocation is unnecessary and often leads to just redundant tests!
| METHODS FOR VERIFICATION | DESCRIPTION |
|---|---|
| verify( T mock).someMethod(); verify( T mock, times(int n) ).someMethod(); verify( T mock, atLeast(int n) ).someMethod(); verify( T mock, atLeastOnce() ).someMethod(); verify( T mock, atMost(int n) ).someMethod(); verify( T mock, never() ).someMethod(); | Verify that someMethod was called specified number of times. Default is once. |
| verifyZeroInteractions( Object... mocks ); | Verify that there have been no method calls on the mock object(s) |
| verifyNoMoreInteractions( Object... mocks ) | Verify that there have been no additional method calls on the mock object(s) besides what has already been verified. |
Stubbing methods using when()
Stubbing is used to specify method behaviors on mock objects.
We have already seen an example of stubbing:
Mockito.when(requestMock.getAttribute("email")).thenReturn("xyz@abc.com");
Argument matchers can be used in stubs to match the invocation with any specified argument:
In the below example, any invocation of getAttribute() with a String parameter will return the string “xyz@abc.com”.
Mockito.when(requestMock.getAttribute(Mockito.anyString()))
.thenReturn("xyz@abc.com");
Sometimes, we might have to test exception handling. How would my code handle if an exception is thrown by getAttribute()
Mockito.when(requestMock.getAttribute(Mockito.anyString())).thenThrow(new RuntimeException());
when() would work only for non-void methods!
| STUBBING WITH MOCKITO | USAGE |
|---|---|
| when | Only for non-void methods |
| when( mock.method() ).thenCallRealMethod(); when( mock.method() ).thenReturn(T value); when( mock.method() ).thenReturn(T value, T... values); when( mock.method() ).thenThrow(Throwable... throwables); when( mock.method() ).thenAnswer(Answer> answer); |
|
This should get you started with some basic unit tests with Mockito. Have fun !!
Future articles in the series:
- Part 2 – Argument Matchers and stubbing void methods
- Part 3 – Partial Mocks using Mockito and Limitations of Mockito
Natural Language Processing – Basics
Nov 18th
Natural Language Processing
- Making computers understand and deal with natural (human) languages like English, Tamil, Spanish, etc.
- Exploiting human cleverness, and not computer cleverness
Natural Language Processing is a field of Computer Science and Linguistics concerned with the interactions between computers and natural (human) languages.
Categories
| Phonology | study of speech sounds |
| Morphology | study of meaningful components of words |
| Syntax | study of structural relationships between words |
| Semantics | study of meaning |
Phonology
- Modeling the pronunciation of a word as a string of symbols – PHONES
- Involves study of syllables, how they sound and how they group together to produce the word sound.
- Notice the difference in sound of “C” in the following words:
- Coach
- Chair
- Can
Morphology
- Identification, analysis and description of the structure of words.
- Study of structural variations of words
- INFLECTIONS in a word are structural changes, usually through affixes, to express Number, Tense, Case, Gender, Person, etc.
- dog – dogs
- goose – geese
- hunt – hunted
- his – hers
- WORD FORMATIONS includes a group of words that have a specific meaning when they appear together.
- mother in law
- hot dog
Syntax
- Study of grammars
- Syntactic correctness in sentence formation
- Part of Speech tagging
- Noun
- Verb
- Adjective, etc
- I can write : Is “can” AUX VERB or VERB or NOUN?
Semantics
- Understanding and representing the meaning
- Predicate Calculus can be used to represent semantics: Has(Ram, book)
Browse through the below presentation for more information on
- NLP
- Ambiguity resolution
- Perceptions
- Applications of NLP
- Machine Learning
Java vs. .NET – hilarious spoof !!!
Sep 15th
Java Java jing-jing-jing … !
Aug 21st
This song makes me love Java even more I normally do !!!
Audio clip: Adobe Flash Player (version 9 or above) is required to play this audio clip. Download the latest version here. You also need to have JavaScript enabled in your browser.
Java, Java, Java Java jing-jing-jing
Java, Java, Java Java jing-jing-jingIt’s not a cup of coffee but it’s hot as can be
Came pourin’ through the Gates on a “Big Mac” Nealy
Singin’, Java, Java, Java Java jing-jing-jingMicrosoft thought Java really could be a threat
Java through the Windows maybe put them in debt
Gates, he took a license but he altered the feel
Java members all said, “Bill, you’re outta the deal!”
Singin’, Java, Java, Java Java jing-jing-jing
Java, Java, Java Java jing-jing-jingIt’s like a cup of coffee ’cause it’s tasty and fresh
But it’s not really Java if the flavours don’t mesh
Pure Java, Java, Java Java jing-jing-jingMicrosoft released a browser, Java was there
The Sun, it rose and lit up what was really a dare
The RMI, the JNI were missing and lost
Scott said, “Bill, you broke your promise, Now pay the cost!”
Bill said, “Hey, my recipe is richer than yours”
Scott said, “I own the coffee shop, sit down and I’ll pour”
Pour Java, Java, Java Java jing-jing-jing
Java, Java, Java Java jing-jing-jingNobody can tell yet what the future may bring
All we know is Java goes jing-jing-jing
It goes Java, Java, Java Java jing-jing-jing
(Scott really means it)
Java, Java, Java Java jing-jing-jing
(Bill you better believe it)
Java, Java Java jing-jing-jing
Download the song here:
Java Posse Jingle
This song is the intro music of Java Posse podcast, written and performed in 1997 by Loose Bruce Kerr of the Dr. Demento Show and Sun Microsystems attorney.
“Nobody can tell yet what the future may bring” …. 13 years ago !!!
Cloud 20/20 Paper Presentation Contest – Third Place !!
Feb 17th
It was a fantastic day at Bangalore. The Grand Finale of UNISYS Cloud 20/20 Technical Paper Presentation Contest was held at ITC Hotel yesterday. I was one of the finalists and I presented my paper on cloud computing to an audience of 400, which comprised of eminent personalities and stalwarts from the industry. I won the Third Place and was awarded a Nokia N97 mobile phone !!
It all started mid-November. A friend of mine, Venki, informed me about this contest on cloud computing. I went through the details and thought I could put some effort into it. I was not new to Cloud Computing since I had already conducted workshop on that topic in college. I got into action and learnt more about the topic and the challenges faced by this new computing paradigm. I decided to work on application development on the cloud. I came up with a topic: “Realizing Parallelism and Transparency in Applications Through Idempotence”. Wrote an abstract, submitted it, and waited for the results.
I was one among the sixty students shortlisted for the technical paper round. I had about a month to work on my technical paper. I browsed various papers and articles on the topic. Read about the current trends and what kind of applications cloud computing can expect in the future. I thus came up with a pretty decent technical paper, stating the problems and solutions. even though I did not have much hope of getting through to the next round, I eagerly awaited the results.
One evening I got a call telling that I am through to the telephone interview round. This news made me prepare myself well for the interview due to happen the next day. The telephone interview did not go well, since I was literally running and gasping for breath when my phone rang. I could not answer properly, even though I knew the answers. At the end of the day, I had lost all hopes.
But it was a pleasant surprise to see my name listed as one of the six finalists. I had to prepare a presentation for the finals. I worked a lot on it and prepared the slides. I flew to Bangalore and stayed at HM Suites, an excellent place.
The final round was on 15th. I met the other finalists. We got to know each other and became good friends. We had to present our paper to a panel of judges. The panel included eminent geniuses, Bob Supnik (CTO, UNISYS), Dr. Michael Salsburg (Chief Architect, UNISYS) and others. We all were a bit nervous. But the finals went on really well. Results were not announced until the next morning.
The Cloud 20/20 Grand Finale was a fabulous event. A lot of people from UNISYS, HP, Oracle, etc had been present. The entire day was packed with events, seminars and presentations. We were given a chance to present our papers to the audience, and the experience was really great. We were awarded the prizes by Bob Supnik. Deepak from IIIT-B won the first prize, an Apple Macbook Air Laptop. The second place was won by Kiran from IIIT-H, who got a Sony Vaio Laptop. I won the Third Place.
There was also a media event where the media was briefed about the entire event. Our names, I believe, appeared in quite a few papers. But I could get hold of Deccan Chronicle only.
Overall, it was a really great experience. And this was my first technical paper presentation. All thanks to UNISYS for organizing this event successfully and providing me an opportunity to explore more into the world of cloud computing.
Configure NS-2 with Eclipse in Linux
Oct 18th
For most users of NS2, it would be easier if they can use a popular IDE to work with the files.
Here are the step by step instructions I followed to set up NS-2.34 with Eclipse 3.5 in Ubuntu Linux.
In older versions of Eclipse, the settings might be slightly different.
I have compiled the following steps after running into various problems and errors with the setup, and solving them all. So I hope the setup will be smooth for you.
Setting up Eclipse:
- Download Eclipse SDK
- Extract the SDK to a folder
- Open Eclipse
- Go to Help -> Install New Software. In the Work With bar type this:
http://download.eclipse.org/tools/cdt/releases/galileo - Choose CDT Main Features and CDT Optional Features. Install them.
CDT stands for “C/C++ Development Tooling” - If you do not have a working internet connection in the system you have installed Eclipse, instead of steps 4 and 5, download the CDT from the above mentioned site. Then move to Install New Software (see step 4) -> Add and add the archive downloaded.
Installing NS-2
- Download NS-2
- Extract NS-2 to a folder, i.e. /home/username/ns-allinone-2.34
- Edit Makefile:
- Open “…/ns-allinone-2.34/ns-2.34/Makefile.in”and
- Add these lines anywhere near the top of the file:
CCOPT = -g
DEFINE = -DNDEBUG
DEFINE = -DDEBUG - Navigate to …/ns-allinone-2.34/ns-2.34 and run “./configure”
- Navigate to the NS-2 folder using terminal and type ./install
- Also, follow the instructions are displayed at the end of a successful installation. These instructions are to modify the PATH variable and other environment variables as needed.
Adding NS-2 as a Project in Eclipse
- Open Eclipse
- Set the workspace as the ns installation path( /home/username/ns-allinone-2.34 ) by selecting File -> Switch Workspace
- Choose File -> New -> Project -> C++ Project
- Select Project Type as Makefile Project -> Empty C++ Project.
Toolchains: Linux GCC - Enter Project Name as ns-2.34
- Uncheck “Use default location” then browse to the directory NS-2 source directory ( …/ns-allione-2.34/ns-2.34 )
- Select “Next” and “Finish.
- From the workspace, Selecting the NS-2 Project and choosing Project -> Build All should not give Error.
- Running the project must open the console with the NS-2 prompt, %
Setting Debug Configuration:
- Select Run -> Debug Configurations
- Choose C/C++ Application. Type in any name.
- Under the Main tab, Choose the following:
Project as ns-2.34.
C/C++ Application as ns. (Search Project and Choose this) - Under the Debugger tab, choose GDB Debugger. Uncheck the “Stop on startup at” option.
- Apply and Debug.
Update from Readers: Changes to be made in Makefile.in file:
Add -g to the line CCOPT = @V_CCOPT@
CCOPT = @V_CCOPT@ -g
Add -DNDEBUG -DDEBUG to the end of the following line:
DEFINE = -DTCP_DELAY_BIND_ALL -DNO_TK @V_DEFINE@ @V_DEFINES@ @DEFS@-DNS_DIFFUSION -DSMAC_NO_SYNC -DCPP_NAMESPACE=@CPP_NAMESPACE@-DUSE_SINGLE_ADDRESS_SPACE -Drng_test -DNDEBUG -DDEBUG
Special thanks to Ella Taha for notifying me about the correction!





