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
How to mock a byte array by using EasyMock and PowerMock
提问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 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):
如果要测试该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, ..., ...);