Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jMockit: How to expect constructor calls to Mocked objects?

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?

like image 638
Nagendra U M Avatar asked Nov 09 '11 05:11

Nagendra U M


People also ask

What is JMockit Expectations?

An expectation represents a set of invocations to a specific mocked method/constructor that is relevant for a given test. An expectation may cover multiple different invocations to the same method or constructor, but it doesn't have to cover all such invocations that occur during the execution of the test.

What is the difference between JMockit and Mockito?

JMockit will be the chosen option for its fixed-always-the-same structure. Mockito is more or less THE most known so that the community will be bigger. Having to call replay every time you want to use a mock is a clear no-go, so we'll put a minus one for EasyMock. Consistency/simplicity is also important for me.

What are mocked instances?

Instance mocking means that a statement like: $obj = new \MyNamespace\Foo; …will actually generate a mock object. This is done by replacing the real class with an instance mock (similar to an alias mock), as with mocking public methods.

What is JMockit in Java?

First of all, let's talk about what JMockit is: a Java framework for mocking objects in tests (you can use it for both JUnit and TestNG ones). It uses Java's instrumentation APIs to modify the classes' bytecode during runtime in order to dynamically alter their behavior.


1 Answers

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();
}
like image 87
Matthew Farwell Avatar answered Oct 03 '22 03:10

Matthew Farwell