This is from the official JMockit Tutorial:
@Test
public void doSomethingHandlesSomeCheckedException() throws Exception
{
new Expectations() {
DependencyAbc abc;
{
abc.stringReturningMethod();
returns("str1", "str2");
result = new SomeCheckedException();
}
};
new UnitUnderTest().doSomething();
}
Is it possible to state the opposite, that is multiple results and one return - I need to throw 2 exceptions and only then return a good value. Something like this is what Im looking for:
abc.stringReturningMethod();
returns(new SomeCheckedException(), new SomeOtherException(),"third");
This doesn't work, JMockit can't cast those exceptions to String
(which is the return type of stringReturningMethod
)
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.
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.
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.
Write it like this:
abc.stringReturningMethod();
result = new SomeCheckedException();
result = new SomeOtherException();
result = "third";
I don't know if there is a shortcut to do that but you could always record that the method will be called several times:
abc.stringReturningMethod();
result = new SomeCheckedException();
abc.stringReturningMethod();
result = new SomeOtherException();
abc.stringReturningMethod();
result = "third";
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