jMockit:如何期望构造函数调用模拟对象?

发布于 12-14 07:35 字数 422 浏览 6 评论 0原文

我正在对执行一些序列化操作的方法进行单元测试。我打算模拟序列化逻辑。代码如下:

ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));

我创建了以下模拟对象:

@Mocked FileInputStream mockFIS;

@Mocked BufferedInputStream mockBIS;

@Mocked ObjectInputStream mockOIS;

我设置了一个 NonStrictExpectations() 块,我希望在其中期望上述构造函数调用。

关于如何实现这一目标有什么想法吗?

I am unit-testing a method performing some serialization operations. I intend to mock the serialization logic. The code is as below:

ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));

I have created the following mock objects:

@Mocked FileInputStream mockFIS;

@Mocked BufferedInputStream mockBIS;

@Mocked ObjectInputStream mockOIS;

I have setup a NonStrictExpectations() block where I want to expect the above constructor calls.

Any ideas on how I can achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冷︶言冷语的世界2024-12-21 07:35:29

您可以为一组给定的交互指定一组完整的期望。来自 使用 JMockit 进行基于行为的测试

对 doSomething() 方法的可能测试可以练习该案例
在任意数量的之后,SomeCheckedException 被抛出
成功的迭代。假设我们想要(无论出于何种原因)
记录一整套对交互之间的期望
这两个类,我们可以编写如下测试:

@Test
public void doSomethingHandlesSomeCheckedException() throws Exception
{
  new Expectations() {
     DependencyAbc abc;

     {
        new DependencyAbc(); // expect constructor

        abc.intReturningMethod(); result = 3;

        abc.stringReturningMethod();
        returns("str1", "str2");
        result = new SomeCheckedException();
     }
  };

  new UnitUnderTest().doSomething();
}

You can specify a complete set of Expectations for a given set of interactions. From Behavior-based testing with JMockit:

A possible test for the doSomething() method could exercise the case
where SomeCheckedException gets thrown, after an arbitrary number of
successful iterations. Assuming that we want (for whatever reasons) to
record a complete set of expectations for the interaction between
these two classes, we might write the test below:

@Test
public void doSomethingHandlesSomeCheckedException() throws Exception
{
  new Expectations() {
     DependencyAbc abc;

     {
        new DependencyAbc(); // expect constructor

        abc.intReturningMethod(); result = 3;

        abc.stringReturningMethod();
        returns("str1", "str2");
        result = new SomeCheckedException();
     }
  };

  new UnitUnderTest().doSomething();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文