jMockit: How to expect constructor calls to Mocked

2020-04-07 19:06发布

问题:

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