【问题标题】:How to mock a byte array by using EasyMock and PowerMock如何使用 EasyMock 和 PowerMock 模拟字节数组
【发布时间】:2013-09-03 06:07:56
【问题描述】:

我是这样打的:

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

但是我遇到了运行时异常:找不到对象方法!如何解决?

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

【问题讨论】:

  • 为什么要模拟一个字节数组?为什么不简单地创建一个普通的字节数组?
  • 因为我想模拟一个 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; }
  • 我是新手,不知道如何正确编辑代码。原谅我,:(

标签: java easymock powermock


【解决方案1】:

如果你想测试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, ..., ...);

【讨论】:

  • 我已经尝试过您的建议,但失败了。因为我需要在fileCutter中创建一个字节数组,就像byte[] buffer = new byte[10];expectedRead不一样,所以我遇到了意外的调用异常。这就是为什么我必须模拟一个字节数组。
  • 我已经解决了这个问题!真的我不必模拟字节数组。这是我的新代码:EasyMock.expect(mockRandomAccessFile.read((byte[]) EasyMock.anyObject())).andReturn(3);(byte[])EasyMock.anyObject() 将帮助我匹配在@987654330 中调用的任何字节数组@ 方法。现在我已经通过了我的测试!非常感谢你的帮助! :D
  • 如果您的问题得到解决,最好将答案标记为已接受。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-19
  • 1970-01-01
相关资源
最近更新 更多