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?
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.
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.
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.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With