Throw Checked Exceptions from Mocks with Mockito

throw checked Exceptions from mocks with Mockito

Check the Java API for List.

The get(int index) method is declared to throw only the IndexOutOfBoundException which extends RuntimeException.

You are trying to tell Mockito to throw an exception SomeException() that is not valid to be thrown by that particular method call.

To clarify further.

The List interface does not provide for a checked Exception to be thrown from the get(int index) method and that is why Mockito is failing.

When you create the mocked List, Mockito will use the definition of List.class to creates its mock.

The behavior you are specifying with the when(list.get(0)).thenThrow(new SomeException()) doesn't match the method signature in List API, because get(int index) method does not throw SomeException() so Mockito fails.

If you really want to do this, then have Mockito throw a new RuntimeException() or even better throw a new ArrayIndexOutOfBoundsException() since the API specifies that that is the only valid Exception to be thrown.

Getting Mockito Exception : checked exception is invalid for this method

You should use RuntimeException or subclass it. Your method has to declare checked exception (example: findByState(String state) throws IOException;) otherwise use RuntimeException:

 when(userRepository.findByState("Karnataka"))
.thenThrow(new RuntimeException("Exception"));

Issues trying throw checked exception with mockito

Assuming your test method doesn't declare that it throws Exception, the compiler's absolutely right. This line:

when(interfaceMocked.Execute(anyString())).thenThrow(new Exception());

... calls Execute on an instance of Interface1. That can throw Exception, so you either need to catch it or declare that your method throws it.

I would personally recommend just declaring that the test method throws Exception. Nothing else will care about that declaration, and you really don't want to catch it.

checked exception is invalid for this method

You are getting unit testing with mocking wrong. Here:

SimpleClass instanceObj =PowerMockito.mock(SimpleClass.class);

There is no point in mocking the class that is under test!

When you mock that class, you get a stub that has "nothing to do" with your real implementation. A "working setup" would look more like:

public void methodUnderTest(X x, ...) {
try {
x.foo();
} catch (Exception e) {
...
}

and

 X mockedX = mock(X.class);
when(x.foo()).thenThrow(new WhateverException());

underTest.methodUnderTest(mockedX); ...

and then you could try to verify for example that the logger saw that expected logging call. In other words: you either use a mock to allow your code under test to do its job (with you being in control!) or to verify that some expected call took place on a mock object.

But as said: it doesn't make any sense to mock that class that you want to test. Because a mocked object doesn't know anything about the "real" implementation!

Mockito refuses to throw checked exception

I have finally found the solution for this problem.

We have used an anonymous class extending original Sbb class which was tested and in this extended class implementation of mentioned method was altered and throws expression was removed which caused the problem.

I should have read my colleagues code more carefully.

Mockito .thenThrow throws: Checked exception is invalid for this method!

My problem was that I put the annotation @Throws() just into the Service Impl and not into the Interface.

Mockito checked exception is invalid for this method

lookup indeed doesn't throw a ConnectionFactoryException - your code does. Instead, you should throw the correct exception - a NamingException, and test that your code handles it as expected (i.e., throws up a ConnectionFactoryException`):

when(mockContext.lookup("java:comp/env/jdbc/foo"))
.thenThrow(new NamingException("test"));

Check exception invalid for Mockito SQLException throw

I guess the getDbConnection() is a method of DatabaseUtility, and you want to unit test DatabaseUtility class, right?

The "Checked exception is invalid for this method" is as literal as it gets, which means that Mockito only allows the mock to throw Runtime exceptions.

What's more, you may use verify() method provided by Mockito to verify state changing or times-be-called of mocked objects. (And, sorry for any offense, mock means virtualizating other relative modules of the target test module, but leave the target not being mocked so it will go through real logic in code, not fake interfaces provided by unit testing library.)

What is Mocking?

https://www.baeldung.com/mockito-verify

Mockito How to mock and assert a thrown exception?

BDD Style Solution (Updated to Java 8)

Mockito alone is not the best solution for handling exceptions, use Mockito with Catch-Exception

Mockito + Catch-Exception + AssertJ

given(otherServiceMock.bar()).willThrow(new MyException());

when(() -> myService.foo());

then(caughtException()).isInstanceOf(MyException.class);

Sample code

  • Mockito + Catch-Exception + Assertj full sample

Dependencies

  • eu.codearte.catch-exception:catch-exception:2.0
  • org.assertj:assertj-core:3.12.2


Related Topics



Leave a reply



Submit