Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JMockit multiple exceptions as result for method call

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)

like image 296
Queequeg Avatar asked Jan 14 '13 12:01

Queequeg


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 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.

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.


2 Answers

Write it like this:

    abc.stringReturningMethod();
    result = new SomeCheckedException();
    result = new SomeOtherException();
    result = "third";
like image 155
Rogério Avatar answered Sep 21 '22 11:09

Rogério


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";
like image 41
assylias Avatar answered Sep 20 '22 11:09

assylias