jMockit: How to expect constructor calls to Mocked objects?

旧时模样 提交于 2019-12-30 21:03:21

问题


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?


回答1:


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();
}


来源:https://stackoverflow.com/questions/8060735/jmockit-how-to-expect-constructor-calls-to-mocked-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!