【问题标题】:Easymock mocking inputstream read operationEasymock 模拟输入流读取操作
【发布时间】:2014-02-27 06:39:20
【问题描述】:

我想用 easymock 测试以下代码。我已经创建了模拟套接字和模拟输入流,但我无法模拟读取方法。谁能帮帮我

byte[] lenbuf = new byte[2];
sock.getInputStream().read(lenbuf);

我正在尝试关注我的单元测试

InputStream mockInputStream = createMock(InputStream.class);
expect(mockInputStream.read(new byte[2])).andReturn(2);
replay(mockInputStream);

它给了我以下错误

  Unexpected method call InputStream.read([0, 0]):
  InputStream.read([0, 0]): expected: 1, actual: 0

谢谢

【问题讨论】:

  • 使用匹配器。 EasyMock.aryEq()EasyMock.capture() 取决于您要如何测试它。

标签: java unit-testing easymock


【解决方案1】:

(顺便说一句:尝试使用(byte[]) EasyMock.anyObject() 而不是new byte[2] 作为要读取的参数。)

模拟输入流需要做很多工作,并不值得去做。有很多方法可以获取测试可以设置的假输入流,而无需使用模拟对象。试试这个:

String fakeInput = "This is the string that your fake input stream will return";
StringReader reader = new StringReader(fakeInput);
InputStream fakeStream = new ReaderInputStream(reader);

注意 ReaderInputStream 在Apache Commons IO

您也可以在没有 Reader 的情况下使用 StringBufferInputStream。这不需要 Commons IO。它有不足之处,但对于测试代码来说可能已经足够了。

事实上,与其他形式的伪装相比,嘲讽一般来说是一项艰苦的工作。只有当我想证明我的类的内部被测试以特定的方式做某事时,我才会这样做,而这并不是测试的真正目的:好的测试证明接口工作,并允许实现改变。阅读著名的 Martin Fowler 的 definition of mocks 和 Andrew Trenk 的 some of the problems they can introduce

【讨论】:

  • +1 为您的存根建议。跟着它,它使我的测试变得简单:) 谢谢
【解决方案2】:

使用 EasyMock#expect 时,您必须在目标类和单元测试中使用相同的对象。 在目标类的new byte[2] 和单元测试的new byte[2] 中是不同的对象。 您可能希望通过参数或接口传递对象。

例子:

// Unit test
@Test
public targetMethodTest() {
    InputStream mockInputStream = createMock(InputStream.class);
    byte[] lenbuf = new byte[2];
    expect(mockInputStream.read(lenbuf)).andReturn(2);
    replay(mockInputStream);
    ...
    targetClass.targetMethod(lenbuf);
}

...

// target method in target class
public void targetMethod(byte[] lenbuf) {
    ...
    sock.getInputStream().read(lenbuf);
}

如果你不关心lenbuf的值,你可以用anyObject()代替new byte[2]

expect(mockInputStream.read(anyObject())).andReturn(2);

【讨论】:

    【解决方案3】:

    试试这个:

    InputStream mockInputStream = IOUtils.toInputStream("fake string", StandardCharsets.UTF_8);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-03
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多