and still may not

Category: utilities

JUnit runs test methods in whatever order it wants, which is generally fine as long as all your test methods are independent of each other. This, though, may not be the case when you’re writing integration tests, where you could have a sequence of operations like

I found some alternative solutions in this stackoverflow question, but they require annotating your methods with tags to specify the order in which you want them to run. What I’d like them to do is just run in the same order as they appear in the source code for the test class. Among the answers, I just found this blog post that achieves the same result as I did, only it looks somewhat more complicated (it involves writing/including several classes).

My solution is fairly simple, but there’s 2 warnings:

it uses Javassist, so if you don’t want to add libraries, there’s that

it only works as long as you don’t have test classes that extend other test classes, and you don’t override all @Test-annotated methods in the subclass (I’ve never done that, but I guess as tests get complicated, you may have that); this can be fixed quite easily though, you just need to add the logic for what should come first according to your needs

On with the code!

You can grab the source straight from this pastebin, or copy/paste it from here (I added the MIT License, I think it should be the most permissive.. my intent is to say “do whatever the heck you want with this code”)

/*
* Copyright (C) <2014> <Michele Bonazza>
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* A test runner that runs tests according to their position in the source file
* of the test class.
*
* @author Michele Bonazza
*/
public class OrderedTestRunner extends BlockJUnit4ClassRunner {
/**
* Creates a new runner
*
* @param clazz
* the class being tested
* @throws InitializationError
* if something goes wrong
*/
public OrderedTestRunner(Class<?> clazz) throws InitializationError {
super(clazz);
}
/*
* (non-Javadoc)
*
* @see org.junit.runners.BlockJUnit4ClassRunner#computeTestMethods()
*/
@Override
protected List<FrameworkMethod> computeTestMethods() {
// get all methods to be tested
List<FrameworkMethod> toSort = super.computeTestMethods();
if (toSort.isEmpty())
return toSort;
// a map containing <line_number, method>
final Map<Integer, FrameworkMethod> testMethods = new TreeMap<>();
// check that all methods here are declared in the same class, we don't
// deal with test methods from superclasses that haven't been overridden
Class<?> clazz = getDeclaringClass(toSort);
if (clazz == null) {
// fail explicitly
System.err
.println("OrderedTestRunner can only run test classes that"
+ " don't have test methods inherited from superclasses");
return Collections.emptyList();
}
// use Javassist to figure out line numbers for methods
ClassPool pool = ClassPool.getDefault();
try {
CtClass cc = pool.get(clazz.getName());
// all methods in toSort are declared in the same class, we checked
for (FrameworkMethod m : toSort) {
String methodName = m.getName();
CtMethod method = cc.getDeclaredMethod(methodName);
testMethods.put(method.getMethodInfo().getLineNumber(0), m);
}
} catch (NotFoundException e) {
e.printStackTrace();
}
return new ArrayList<>(testMethods.values());
}
private Class<?> getDeclaringClass(List<FrameworkMethod> methods) {
// methods can't be empty, it's been checked
Class<?> clazz = methods.get(0).getMethod().getDeclaringClass();
for (int i = 1; i < methods.size(); i++) {
if (!methods.get(i).getMethod().getDeclaringClass().equals(clazz)) {
// they must be all in the same class
return null;
}
}
return clazz;
}
}

to use this, you need to add Javassist to your classpath; if you have a Maven project, it’s incredibly easy to do so, just add this to your POM:

About warning 2. above, in case you have something like MyTestClass extends BaseTestClass and you have methods annotated with @Test in BaseTestClass that aren’t overridden by MyTestClass, OrderedTestRunner will just fail printing the message you can see at line 50 above on System.err. I did this because I don’t think there’s a well-defined order in that case (should all methods from the super class run first? Should that go all the way up in the class hierarchy?), so you can adjust it to fit your particular needs.

This is something I noticed on Android, but from what I read it also involves the desktop Java version.

I was sending POST requests to an API server, and I was getting some random 400 Bad Request responses from time to time. I wish Apache provided an easy way to log the plain text version of Http requests, but I couldn’t find a better way to see what the app was sending than sending the same request to my PC when failing.

I don’t know if it’s my router, but sometimes connections from the Android device to my PC get blocked: to make them work I just open a browser on the Android, go to some website and then try again with my internal IP (192.168.0.whatever). It always works, no idea why.

Using this code I discovered that my post requests were executed 4 times each, nearly at the same time. I discovered that it’s the default behavior, and you must provide your own RetryHandler if you want the HttpClient to work otherwise.

In my case, my calls are sent to Google’s shortener service, and for some reason sometimes it just rejects requests. If you wait a little bit between attempts you increase your chance of getting valid responses. So this is what I did:

where debugPost() is a method that calls my PC to log the request, and Utils.debug() is just a small utility method I wrote to log messages with logcat using String.format() if format args are passed to it (it also takes care of splitting messages that would be truncated by logcat itself).

You could choose to implement exponential backoff very easily, but since it’s a blocking operation for the user in my case I preferred not to.

This is a thing that I’m sure a lot of Java programmers have come with an implementation for, but no minimal examples were easy to be found when I looked for it. And it was fun to code, too, so I’ll share it!

Many many times I find myself wanting to declare a simple function to be executed on all items in a list, much like I do in Python with lambdas. What I usually do is just write a separate method if I find myself doing this same thing several times, and call that method all over. This is boring, though!

With lambda functions I find this task a little less boring and, most of all, I can use the same scheme wherever I need it and it speeds up my work since my brain seems to enjoy this process much better..

This is the LambdaFunction interface:

/**
* A function to be executed on all items in a list.
*
* <p>
* This is a verbose Java equivalent of lambda functions; it's verbose
* because you must declare a (private anonymous) class to define the lamba
* function.
*
* <p>
* This is how you would use it:
*
* <blockquote>
*
* <pre>
* List<MyClass> myList = Arrays.asList(new MyClass("one"), new MyClass("two"));
* Utils.executeAll(myList, new LambdaFunction<MyClass>() {
* public void execute(MyClass item) {
* // call one of MyClass methods
* item.foo();
* }
* }
* </pre>;
*
* </blockquote>; Where of course the {@link LambdaFunction} can be stored to
* be reused several times.
*
* @author mb
*
* @param <T>
* the type of elements in the list on which the lambda function
* must be executed
* @see Utils#callOnAll(List, LambdaFunction)
* @see Utils#callOnAll(Object[], LambdaFunction)
*/
public static interface LambdaFunction<T> {
/**
* The function called on all items in the list.
*
* @param item
* the item onto which the function must be called
*/
public void execute(T item);
}

(The interface is static just because in my code it’s in the same file as the Utils class, but you can put it in a separate file if you want).

As the javadoc explains, you use it in combination with the Utils.callOnAll() method. Here are the two flavors:

Yes, I could have just added a private void enableHandlers(boolean areEnabled) method in this case, but I prefer to pollute my classes with as few private utility methods as possible; private fields are hidden by Eclipse, so I never even pay attention to them. Plus, if I didn’t need to call HANDLER_ENABLER several times I could have had a true(r) lambda function:

Everybody has a different opinion on whether you should write unit tests for private methods, and my own is that you should, unless said methods are very small procedures called by some public function, in which case you can treat the whole package as a black box.

Unfortunately, several classes contain code that is completely irrelevant to users of the class, or code that should never be called directly if not from within the class itself (because you’re proxying calls to control accesses to the class, or keeping stats, or demultiplexing calls from several classes, or whatever). The purpose of unit-testing is to help maintain the code, and to help spotting bugs more quickly; it shouldn’t become self-referential and it definitely should not change the way you structure your classes, just for the sake of testability. Hence, private methods should be used whenever you don’t want to expose the internal workings of a class to outsiders, but at the same time they shouldn’t be left behind when writing tests, or they quickly become a source of subtle errors.

I like PowerMock‘s mockPrivate feature, and I use it a lot, but what I want to do here is to actually test the private method, not replace it with a mock! (I know it should be obvious, but when using powermock very often you start to think of it as the solution to all your problems)

Reflection comes in handy: you set methods accessibility flag to true and you can call them! You can also change the value of private fields, or call private constructors. I mostly use these 3 functions, so I came up with a simple class that I use in all my Java JUnit-driven projects.

In the spirit of my previous post on some of my favorite Java utility methods, I’ll post here this class, hoping that some of you may find it useful:

/**
* ReflectionUtils.java
* Created on Apr 30, 2012
* Copyright 2012 mb
* <https://somethingididnotknow.wordpress.com>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
* Some utility methods that can be used for unit tests to alter internal
* objects states by exploiting features from <tt>java.lang.reflect</tt>
* package.
*
* @author mb
*/
public class ReflectionUtils {
/**
* Sets the value of the <tt>static</tt> field named <tt>fieldName</tt> in
* class <tt>clazz</tt> to <tt>newValue</tt> and returns <code>true</code>
* if the operation was successful.
*
* @param clazz
* the class whose field is to be changed
* @param fieldName
* the (case-sensitive) name of the field whose content is to be
* changed
* @param newValue
* the new value that the field should store
* @return <code>true</code> if the new value has been set,
* <code>false</code> otherwise
*/
public static boolean changeStaticField(Class<?> clazz, String fieldName,
Object newValue) {
if (clazz == null)
return false;
return change(clazz, null, fieldName, newValue);
}
private static boolean change(Class<?> clazz, Object object,
String fieldName, Object newValue) {
boolean success = false;
try {
Field toChange = clazz.getDeclaredField(fieldName);
toChange.setAccessible(true);
toChange.set(object, newValue);
success = true;
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return success;
}
private static Object call(Class<?> clazz, Object object,
String methodName, Object... args) throws IllegalArgumentException,
InvocationTargetException {
Method[] allMethods = clazz.getDeclaredMethods();
for (Method m : allMethods) {
// cycling through all methods, as we don't want users to specify
// the list of argument types, we rely on the compiler
if (m.getName().equals(methodName)) {
m.setAccessible(true);
try {
Object result = m.invoke(object, args);
return result;
} catch (IllegalAccessException e) {
} catch (IllegalArgumentException e) {
}
}
}
throw new IllegalArgumentException(
String.format(
"No matching method has been found for method named %s and parameters %s",
methodName, Arrays.toString(args)));
}
/**
* Invokes the method called <tt>methodName</tt> on <tt>object</tt> passing
* the provided arguments to it, returning the result if the invocation was
* successful, throwing an {@link IllegalArgumentException} otherwise.
*
* @param object
* the object onto which the method is to be invoked
* @param methodName
* the (case-sensitive) name of the method to be called
* @param args
* the arguments to be passed to the method
* @return the value returned by the method
* @throws IllegalArgumentException
* in case a method called <tt>methodName</tt> accepting the
* provided list of arguments is not found, or <tt>object</tt>
* is <code>null</code>
* @throws InvocationTargetException
* in case the method threw an exception (that can be retrieved
* calling {@link InvocationTargetException#getCause()} on the
* caught exception)
*/
public static Object callMethod(Object object, String methodName,
Object... args) throws IllegalArgumentException,
InvocationTargetException {
if (object == null || methodName == null)
throw new IllegalArgumentException("null object or method name");
return call(object.getClass(), object, methodName, args);
}
/**
* Invokes the method called <tt>methodName</tt> of class <tt>clazz</tt>
* passing the provided arguments to it, returning the result if the
* invocation was successful, throwing an {@link IllegalArgumentException}
* otherwise.
*
* @param clazz
* the class whose method is to be invoked
* @param methodName
* the (case-sensitive) name of the method to be called
* @param args
* the arguments to be passed to the method
* @return the value returned by the method
* @throws IllegalArgumentException
* in case a method called <tt>methodName</tt> accepting the
* provided list of arguments is not found, or <tt>object</tt>
* is <code>null</code>
* @throws InvocationTargetException
* in case the method threw an exception (that can be retrieved
* calling {@link InvocationTargetException#getCause()} on the
* caught exception)
*/
public static Object callStaticMethod(Class<?> clazz, String methodName,
Object... args) throws IllegalArgumentException,
InvocationTargetException {
if (clazz == null || methodName == null)
throw new IllegalArgumentException("null class or method name");
return call(clazz, null, methodName, args);
}
/**
* Sets the value of the field named <tt>fieldName</tt> for object
* <tt>object</tt> to <tt>newValue</tt> and returns <code>true</code> if the
* operation was successful.
*
* @param object
* the object whose field is to be changed
* @param fieldName
* the (case-sensitive) name of the field whose content is to be
* changed
* @param newValue
* the new value that the field should store
* @return <code>true</code> if the new value has been set,
* <code>false</code> otherwise
*/
public static boolean changeField(Object object, String fieldName,
Object newValue) {
if (object == null)
return false;
return change(object.getClass(), object, fieldName, newValue);
}
/**
* Creates a new object of type <tt>T</tt> by calling a constructor of class
* <tt>clazz</tt> accepting the provided list of <tt>args</tt>.
*
* @param <T>
* the type of the object to be created
* @param clazz
* the class of the object to be created (remember, it's
* <tt>Class&lt;T&gt;</tt>)
* @param args
* the arguments to feed the constructor with
* @return the created object or <code>null</code> if anything goes wrong
* @throws InvocationTargetException
* in case the matching constructor throws an <tt>Exception</tt>
* (that can be retrieved calling
* {@link InvocationTargetException#getCause()} on the caught
* exception) when called
*/
public static <T> T createNew(Class<T> clazz, Object... args)
throws InvocationTargetException {
if (clazz == null)
return null;
Constructor<?>[] allConstructors = clazz.getDeclaredConstructors();
for (Constructor<?> c : allConstructors) {
// cycling through all constructors, as we don't want users to
// specify
// the list of argument types, we rely on the compiler
c.setAccessible(true);
try {
Object result = c.newInstance(args);
return clazz.cast(result);
} catch (IllegalAccessException e) {
} catch (IllegalArgumentException e) {
} catch (InstantiationException e) {
e.printStackTrace();
}
}
throw new IllegalArgumentException(
String.format(
"No matching constructor has been found for class %s and parameters %s",
clazz, Arrays.toString(args)));
}
}

The weird for loop in call() and createNew() is there because I don’t want to specify the type of every argument to be passed along to methods or constructors, so I can’t use getDeclaredMethod() or getDeclaredConstructor(). This is testing code, so usability should be favored over performance, I guess…

Whenever I start a new project in Java I always find myself in need of some basic utility methods that are lacking in the standard library. I suppose that every programmer has his own little “bag of tricks” for every language (well, maybe not for python.. ❤ ).. and this is mine!

These are only some of the methods I use the most, of course, those that may be useful for many people 🙂

/*
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details.
*/
import java.util.List;
import java.util.Set;
/**
* Contains only a bunch of <code>static</code> utility methods.
*
* @author mb - somethingididnotknow.wordpress.com
*/
public final class Utilities {
/**
* Checks whether <strong>all</strong> the provided objects are
* <code>null</code>.
*
* @param objects
* a number of objects of any kind that are to be checked
* against <code>null</code>
* @return <code>true</code> in case <strong>all</strong> the argument
* objects are <code>null</code>, <code>false</code> otherwise.
*/
public static boolean areAllNull(Object... objects) {
for (Object o : objects) {
if (o != null)
return false;
}
return true;
}
/**
* Checks whether <strong>any</strong> of the argument objects is
* <code>null</code>.
*
* @param objects
* a number of objects of any kind that are to be checked
* against <code>null</code>.
* @return <code>true</code> if at least one of the arguments is
* <code>null</code>.
*/
public static boolean isAnyNull(Object... objects) {
for (Object o : objects) {
if (o == null)
return true;
}
return false;
}
/**
* Checks whether the two arguments are equal using a <em>null-safe</em>
* comparison.
*
* In case only one of the two objects is <code>null</code>,
* <code>false</code> is returned. In case both are not <code>null</code>
* {@link Object#equals(Object)} is called on the first object using the
* second as argument.
*
* @param first
* the first object to be checked.
* @param second
* the second object to be checked.
* @return <code>true</code> in case {@link Object#equals(Object)} returns
* <code>true</code> or the objects are both <code>null</code>,
* <code>false</code> otherwise.
*/
public static boolean nsEquals(Object first, Object second) {
if (first == null)
return second == null;
if (second == null)
return false;
return first.equals(second);
}
/**
* Returns a String that is empty in case the argument <tt>string</tt> is
* <code>null</code>, the unmodified <tt>string</tt> otherwise.
*
* @param string
* the string to be checked against <code>null</code>
* @return the empty String if <tt>string</tt> is <code>null</code>, the
* argument <tt>string</tt> unmodified otherwise
*/
public static String nonNull(final String string) {
return string == null ? "" : string;
}
/**
* An equivalent of Python's <code>str.join()</code> function on lists: it
* returns a String which is the concatenation of the strings in the
* argument array. The separator between elements is the argument
* <tt>toJoin</tt> string. The separator is only inserted between
* elements: there's no separator before the first element or after the
* last.
*
* @param toJoin
* the separator, if <code>null</code> the empty String is used
* @param list
* a list of <code>Object</code>s on which
* {@link Object#toString()} will be called
* @return the concatenation of String representations of the objects in
* the list
*/
public static String join(String toJoin, Object[] list) {
if (list == null || list.length == 0)
return "";
StringBuilder builder = new StringBuilder();
String delimiter = nonNull(toJoin);
int i = 0;
for (; i < (list.length - 1); i++) {
if (list[i] != null)
builder.append(list[i]);
builder.append(delimiter);
}
builder.append(list[i]);
return builder.toString();
}
/**
* An equivalent of Python's <code>str.join()</code> function on lists: it
* returns a String which is the concatenation of the strings in the
* argument list. The separator between elements is the string providing
* this method. The separator is only inserted between elements: there's
* no separator before the first element or after the last.
*
* @param toJoin
* the separator, if <code>null</code> the empty String is used
* @param list
* a list of <code>Object</code>s on which
* {@link Object#toString()} will be called
* @return the concatenation of String representations of the objects in
* the list
*/
public static String join(String toJoin, List list) {
if (list == null || list.isEmpty())
return "";
StringBuilder builder = new StringBuilder();
String delimiter = nonNull(toJoin);
int i = 0;
for (; i < list.size() - 1; i++) {
if (list.get(i) != null)
builder.append(list.get(i));
builder.append(delimiter);
}
builder.append(list.get(i));
return builder.toString();
}
/**
* An equivalent of Python's <code>str.join()</code> function on lists: it
* returns a String which is the concatenation of the strings in the
* argument list. The separator between elements is the string providing
* this method. The separator is only inserted between elements: there's
* no separator before the first element or after the last.
*
* @param toJoin
* the separator, if <code>null</code> the empty String is used
* @param set
* a set of <code>Object</code>s on which
* {@link Object#toString()} will be called
* @return the concatenation of String representations of the objects in
* the set
*/
public static String join(String toJoin, Set set) {
return join(toJoin, set.toArray());
}
/**
* Checks whether the argument <tt>array</tt> contains at least a
* <code>null</code> value.
*
* @param array
* the array to be checked.
* @return <code>true</code> in case <em>at least</em> one of the values
* stored in the argument <tt>array</tt> is <code>null</code>, or
* in case the <tt>array</tt> itself is <code>null</code>.
*/
public static boolean containsNull(Object[] array) {
if (array == null)
return true;
for (Object o : array) {
if (o == null)
return true;
}
return false;
}
/**
* Checks whether the argument <tt>list</tt> contains at least a
* <code>null</code> value.
*
* @param list
* the list to be checked
* @return <code>true</code> in case <em>at least</em> one of the values
* stored in the argument <tt>array</tt> is <code>null</code>, or
* in case the <tt>list</tt> itself is <code>null</code>
*/
public static boolean containsNull(List list) {
if (list == null)
return true;
for (Object o : list) {
if (o == null)
return true;
}
return false;
}
/**
* Checks whether the argument <tt>string</tt> is <code>null</code> or
* empty. Please note that the <tt>string</tt> is
* <strong>trimmed</strong>, so that a check on a string containing
* white spaces only will always return <code>true</code>.
*
* @param string
* the string to be checked
* @return <code>true</code> in case the argument <tt>string</tt> is
* <code>null</code>, empty ({@link String#length()} returns 0) or
* contains only white spaces (
* <tt>{@link String#trim()}.length()</tt> returns 0)
*/
public static boolean isNullOrEmpty(String string) {
return string == null || string.trim().length() == 0;
}
}