Java 如何使用 EasyMock 和 PowerMock 模拟字节数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18585250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:16:21  来源:igfitidea点击:

How to mock a byte array by using EasyMock and PowerMock

javaeasymockpowermock

提问by Rekoolno

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):

[编辑] 我想模拟一个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;
}

回答by LaurentG

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

如果要测试该fileCutter方法,则不需要模拟byte数组。你必须嘲笑RandomAccessFile。例如,像这样(对不起,小的语法错误,我现在无法检查):

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, ..., ...);