Testing with Live Devices
26 Sep 2008In a lot of the projects I work on the software we write must communicate with other live devices that speak a variety of protocols and testing using mock objects will only get you so far. That is why I like to capture actual data that is coming out of these devices and include it directly in my unit tests.
public class ByteArrayUtils {
private ByteArrayUtils() {}
public static byte[] fromHexString(final String encoded) {
if ((encoded.length() % 2) != 0)
throw new IllegalArgumentException("Input must contain " +
"an even number of characters");
final byte result[] = new byte[encoded.length()/2];
StringBuffer buf = new StringBuffer(encoded);
for (int i = 0; i < buf.length(); i += 2) {
result[i/2] = (byte) Integer.parseInt(buf.substring(i, i+2), 16);
}
return result;
}
public static String toHexString(byte[] data) {
if (data == null) return "";
StringBuffer buf = new StringBuffer(data.length * 2);
for (int i = 0; i < data.length; i++) {
String ch = Integer.toHexString(data[i] & 0xff);
if (ch.length() == 1) {
buf.append("0");
}
buf.append(ch);
}
return buf.toString();
}
}
Using this class allows me to convert byte arrays into strings that I can then include directly in my unit test cases. You can then inject the byte array into you code, and its just like having the real device there (well sorta)