Testing with Live Devices
In 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | 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)
Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.



Comments
No comments yet.
Leave a comment