14 December 2010

Cast/convert Object to byte[] array for Dbunit

If you are using Dbunit you might want to verify that the data in a BLOB is correct:

IDataSet dataSet = idatabaseConnection.createDataSet();
ITable myTable = dataSet.getTable("my_table");
Object blob = myTableDbUnit.getValue(0, "myBlob")

But now what? The blob cannot be converted or casted to a byte[] in Java! Here is solution:
    private static byte[] toByteArray(Object object) {
        int length = Array.getLength(object);
        byte[] result = new byte[length];
        for (int i = 0; i < length; i++) {
            result[i] = Array.getByte(object, i);
        return result;

byte[] blob = toByteArray(myTableDbUnit.getValue(0, "myBlob"));

No comments:

Post a Comment