1. Overview
This article is the second installment in the JMockit series. You may want to read the first article as we are assuming that you are already familiar with JMockit’s basics.
Today we’ll go deeper and focus on expectations. We will show how to define more specific or generic argument matching and more advanced ways of defining values.
2. Argument Values Matching
The following approaches apply both to Expectations as well as Verifications.
2.1. “Any” Fields
JMockit offers a set of utility fields for making argument matching more generic. One of these utilities is the anyX field.
These will check that any value was passed and there is one for each primitive type (and the corresponding wrapper class), one for strings, and a “universal” one of type Object.
Let’s see an example:
public interface ExpectationsCollaborator {
String methodForAny1(String s, int i, Boolean b);
void methodForAny2(Long l, List<String> lst);
}
@Test
public void test(@Mocked ExpectationsCollaborator mock) throws Exception {
new Expectations() {{
mock.methodForAny1(anyString, anyInt, anyBoolean);
result = "any";
}};
Assert.assertEquals("any", mock.methodForAny1("barfooxyz", 0, Boolean.FALSE));
mock.methodForAny2(2L, new ArrayList<>());
new FullVerifications() {{
mock.methodForAny2(anyLong, (List<String>) any);
}};
}
We should take into account that when using any field, we need to cast it to the expected type. The complete list of fields is present in the documentation.
2.2. “With” Methods
JMockit also provides several methods to help with generic argument matching. Those are the withX methods.
These allow for a little more advanced matching than the anyX fields. We can see an example here in which we’ll define an expectation for a method that will be triggered with a string containing foo, an integer not equal to 1, a non-null Boolean, and any instance of the List class:
public interface ExpectationsCollaborator {
String methodForWith1(String s, int i);
void methodForWith2(Boolean b, List<String> l);
}
@Test
public void testForWith(@Mocked ExpectationsCollaborator mock) throws Exception {
new Expectations() {{
mock.methodForWith1(withSubstring("foo"), withNotEqual(1));
result = "with";
}};
assertEquals("with", mock.methodForWith1("barfooxyz", 2));
mock.methodForWith2(Boolean.TRUE, new ArrayList<>());
new Verifications() {{
mock.methodForWith2(withNotNull(), withInstanceOf(List.class));
}};
}
We can see the complete list of withX methods on JMockit’s documentation.
It’s important to take into account that the special with(Delegate) will be covered in its own subsection.
2.3. Null Is Not Null
Something that is good to understand sooner than later is that null is not used to define an argument for which null has been passed to a mock.
Actually, null is used as syntactic sugar to define that any object will be passed (so it can only be used for parameters of reference type). To specifically verify that a given parameter receives the null reference, the withNull() matcher can be used.
For the next example, we’ll define the behavior for a mock, that should be triggered when the arguments passed are: any string, any List, and a null reference:
public interface ExpectationsCollaborator {
String methodForNulls1(String s, List<String> l);
void methodForNulls2(String s, List<String> l);
}
@Test
public void testWithNulls(@Mocked ExpectationsCollaborator mock){
new Expectations() {{
mock.methodForNulls1(anyString, null);
result = "null";
}};
assertEquals("null", mock.methodForNulls1("blablabla", new ArrayList<String>()));
mock.methodForNulls2("blablabla", null);
new Verifications() {{
mock.methodForNulls2(anyString, (List<String>) withNull());
}};
}
Note the difference: null means any list and withNull() means a null reference to a list. In particular, this avoids the need to cast the value to the declared parameter type (see that the third argument had to be cast but not the second one).
The only condition to be able to use this is that at least one explicit argument matcher had been used for the expectation (either a with method or any field).
2.4. “Times” Field
Sometimes, we want to constrain the number of invocations expected for a mocked method. For this, JMockit has the reserved words times, minTimes, and maxTimes (all three allow non-negative integers only):
public interface ExpectationsCollaborator {
void methodForTimes1();
void methodForTimes2();
void methodForTimes3();
}
@Test
public void testWithTimes(@Mocked ExpectationsCollaborator mock) {
new Expectations() {{
mock.methodForTimes1(); times = 2;
mock.methodForTimes2();
}};
mock.methodForTimes1();
mock.methodForTimes1();
mock.methodForTimes2();
mock.methodForTimes3();
mock.methodForTimes3();
mock.methodForTimes3();
new Verifications() {{
mock.methodForTimes3(); minTimes = 1; maxTimes = 3;
}};
}
In this example, we’ve defined that exactly two invocations (not one, not three, exactly two) of methodForTimes1() should be done using the line times = 2;.
Then we used the default behavior (if no repetition constraint is given minTimes = 1; is used) to define that at least one invocation will be done to methodForTimes2().
Lastly, using minTimes = 1; followed by maxTimes = 3; we defined that between one and three invocations would occur to methodForTimes3().
Take into account that both minTimes and maxTimes can be specified for the same expectation, as long as minTimes is assigned first. On the other hand, times can only be used alone.
2.5. Custom Argument Matching
Sometimes argument matching is not as direct as simply specifying a value or using some of the predefined utilities (anyX or withX). For that cases, JMockit provides with(Delegate) method.
Let’s see an example of matching a specific class to a passed object:
public interface ExpectationsCollaborator {
void methodForArgThat(Object o);
}
public class Model {
public String getInfo(){
return "info";
}
}
@Test
public void testCustomArgumentMatching(@Mocked ExpectationsCollaborator mock) {
new Expectations() {{
mock.methodForArgThat(with(new Delegate<Object>() {
public boolean matches(Object item) {
return item instanceof Model && "info".equals(((Model) item).getInfo());
}
}));
}};
mock.methodForArgThat(new Model());
}
3. Returning Values
Let’s now look at the return values; keep in mind that the following approaches apply only to Expectations as no return values can be defined for Verifications.
3.1. Result and Returns (…)
When using JMockit, we have three different ways of defining the expected result of the invocation of a mocked method. Of all three, we’ll talk now about the first two (the simplest ones) which will surely cover 90% of everyday use cases.
These two are the result field and the returns(Object…) method:
- With the result field, we can define one return value for any non-void returning mocked method. This return value can also be an exception to be thrown (this time working for both non-void and void returning methods).
- Several result field assignations can be done in order to return more than one value for more than one method invocations (we can mix both return values and errors to be thrown).
- The same behavior will be achieved when assigning to the result a list or an array of values (of the same type as the return type of the mocked method, NO exceptions here).
- The returns(Object…) method is syntactic sugar for returning several values at the same time.
This is more easily shown with a code snippet:
public interface ExpectationsCollaborator{
String methodReturnsString();
int methodReturnsInt();
}
@Test
public void testResultAndReturns(@Mocked ExpectationsCollaborator mock) {
new Expectations() {{
mock.methodReturnsString();
result = "foo";
result = new Exception();
result = "bar";
returns("foo", "bar");
mock.methodReturnsInt();
result = new int[]{1, 2, 3};
result = 1;
}};
assertEquals("Should return foo", "foo", mock.methodReturnsString());
try {
mock.methodReturnsString();
fail("Shouldn't reach here");
} catch (Exception e) {
// NOOP
}
assertEquals("Should return bar", "bar", mock.methodReturnsString());
assertEquals("Should return 1", 1, mock.methodReturnsInt());
assertEquals("Should return 2", 2, mock.methodReturnsInt());
assertEquals("Should return 3", 3, mock.methodReturnsInt());
assertEquals("Should return foo", "foo", mock.methodReturnsString());
assertEquals("Should return bar", "bar", mock.methodReturnsString());
assertEquals("Should return 1", 1, mock.methodReturnsInt());
}
In this example, we have defined that for the first three calls to methodReturnsString() the expected returns are (in order) “foo”, an exception, and “bar”. We achieved this using three different assignations to the result field.
Then, we defined that for the fourth and fifth calls, “foo” and “bar” should be returned using the returns(Object…) method.
For the methodReturnsInt() we defined to return 1, 2, and lastly 3 by assigning an array with the different results to the result field, and we defined to return 1 by a simple assignation to the result field.
As we can see there are several ways of defining return values for mocked methods.
3.2. Delegators
To end the article we’re going to cover the third way of defining the return value: the Delegate interface. This interface is used for defining more complex return values when defining mocked methods.
We’re going to see an example of simply explaining:
public interface ExpectationsCollaborator {
int methodForDelegate(int i);
}
@Test
public void testDelegate(@Mocked ExpectationsCollaborator mock) {
new Expectations() {{
mock.methodForDelegate(anyInt);
result = new Delegate() {
int delegate(int i) throws Exception {
if (i < 3) {
return 5;
} else {
throw new Exception();
}
}
};
}};
assertEquals("Should return 5", 5, mock.methodForDelegate(1));
try {
mock.methodForDelegate(3);
fail("Shouldn't reach here");
} catch (Exception e) {
}
}
The way to use a delegator is to create a new instance for it and assign it to a returns field. In this new instance, we should create a new method with the same parameters and return type than the mocked method (we can use any name for it). Inside this new method, use whatever implementation you want in order to return the desired value.
In the example, we did an implementation in which 5 should be returned when the value passed to the mocked method is less than 3 and an exception is thrown otherwise (note that we had to use times = 2; so that the second invocation is expected as we lost the default behavior by defining a return value).
It may seem like quite a lot of code, but in some cases, it’ll be the only way to achieve the result we want.
4. Conclusion
With this, we practically showed everything we need to create expectations and verifications for our everyday tests.
We’ll of course publish more articles on JMockit, so stay tuned to learn even more.
And, as always, the full implementation of this tutorial can be found on the GitHub project.
4.1. Articles in the Series
All articles of the series: