6

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)

Queequeg
  • 2,824
  • 8
  • 39
  • 66

2 Answers2

9

Write it like this:

    abc.stringReturningMethod();
    result = new SomeCheckedException();
    result = new SomeOtherException();
    result = "third";
Rogério
  • 16,171
  • 2
  • 50
  • 63
  • 2
    Won't it set the result for all three calls as `third`? – Queequeg Jan 16 '13 at 10:24
  • Nope. It will record three consecutive results for the `stringReturningMethod()`. (A "result" is either a value to return, an exception to throw, or a `Delegate` to execute. JMockit automatically rewrites these assignments as invocations to its internal methods, that's why it works.) – Rogério Jan 16 '13 at 11:03
  • This doesn't work. You have to do `result = new SomeCheckedException(); result = new SomeOtherException(); returns("Non-exception-String-value");` – searchengine27 Sep 15 '15 at 05:06
2

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";
assylias
  • 321,522
  • 82
  • 660
  • 783
  • I feel like this did NOT work for me I tried it, I tried abc.getCode() result = 1; then abc.getCode() result = new RuntimeException() and it did not work correctly... the other answer worked, however. – Jordan Gee Apr 06 '20 at 22:56