3

I have a method process that returns void and also may throw an exception. I want to verify how does behave other method run while calling process and handles an exception if it occurs.

I've tried to use doThrow() but it tells "Checked exception is invalid for this method!". Then I've tried to use thenThrow() but it needs a not void function.

Code:

public void run() {
    for (var billet : getBillets()) {
        try {
            process(billet);
            billet.status = "processed";
        } catch (Exception e) {
            billet.status = "error";
        }

        billet.update();
    }
}

public void process(Billet billet) throws Exception {
    var data = parse(billet.data); // may throw an exception
    var meta = data.get("meta"); // may throw an exception

    // ... more parsing ...

    new Product(meta).save();
    new Item(meta).save();

    // ... more operations ...
};

Test:

var billet1 = new Billet();
var billet2 = new Billet();

doThrow(new Exception()).when(myInctance).process(billet2);
myInctance.run();
assertEquals("processed", billet1.status);
assertEquals("error", billet2.status);

// ... some checks ...

I expect the test would succeeded.

Aunmag
  • 852
  • 12
  • 17
  • Possible duplicate of [Mockito test a void method throws an exception](https://stackoverflow.com/questions/15156857/mockito-test-a-void-method-throws-an-exception) – Hulk Jan 03 '19 at 10:36
  • That sounds unlikely. My guess is that you oversimplified the code you're sharing, and that the code you really use is different. With the code you're showing there, you wouldn't have the results you're describing. You should show the code that you're really using instead of something else. – kumesana Jan 03 '19 at 10:43
  • 2
    `doThrow` does work for checked exceptions, but you need to throw the correct type of exception according to your method signature. If no checked exceptions are declared, throw a `RuntimeException` instead of `Exception`. – Hulk Jan 03 '19 at 10:44
  • @hulk, thanks. that worked! – Aunmag Jan 03 '19 at 11:04

1 Answers1

5

This is the correct way to tell a mock to throw an exception:

Mockito.doThrow(new SomeException()).when(mock).doSomething()

As Hulk stated in the comments, this exception needs to match the method signature, otherwise, you will get a MockitoException("Checked exception is invalid for this method!")

You could get around that exception by throwing some type of RuntimeException. Lastly, you should try to avoid using a generic Exception. It is far more useful to throw an appropriate named exception.

Phil Ninan
  • 1,108
  • 1
  • 14
  • 23