How to mock a byte array by using EasyMock and PowerMock

14,266

If you want to test the fileCutter method, you don't need to mock a byte array. You have to mock RandomAccessFile. For instance, like this (sorry for small syntax errors, I can't check now):

RandomAccessFile raf = EasyMock.createMock(RandomAccessFile.class);
// replace the byte array by what you expect
byte[] expectedRead = new byte[] { (byte) 129, (byte) 130, (byte) 131};
EasyMock.expect(raf.seek(EasyMock.anyInt()).once();
EasyMock.expect(raf.read(expectedRead)).once();

// If you don't care about the content of the byte array, you can do:
// EasyMock.expect(raf.read((byte[]) EasyMock.anyObject())).once();

myObjToTest.fileCutter(raf, ..., ...);
Share:
14,266
Rekoolno
Author by

Rekoolno

I'm using angular2 to write a product level web app recently. :D

Updated on August 01, 2022

Comments

  • Rekoolno
    Rekoolno almost 2 years

    I tyied just like this:

    byte[] mockByteArray = PowerMock.createMockAndExpectNew(byte[].class, 10);
    

    But I got runtime exception: An object method could not be found! How to fix it?

    [Edit] I want to mock a RandomAccessFile.read(byte[] buffer):

    byte[] fileCutter(RandomAccessFile randomAccessFile, long position, int filePartSize) throws IOException{ 
         byte[] buffer = new byte[filePartSize];
         randomAccessFile.seek(position); 
         randomAccessFile.read(buffer);
         return buffer;
    }