Mockito checked exception is invalid for this method
exception, java, mockito, unit-testing
Solution
`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"));
Problem
I'm getting the error `Checked exception is invalid for this method` when trying to use this mock: ``` InitialContext mockContext; mockContext = mock(InitialContext.class); when((DataSource) mockContext.lookup("java:comp/env/jdbc/foo")).thenThrow(new ConnectionFactoryException("test")); // <-- Fails on this line @Test public void shouldThrowExceptionIfDataSourceDoesNotExist() throws ConnectionFactoryException { assertThatExceptionOfType(ConnectionFactoryException.class) .isThrownBy(() -> { new DataSourceFactory(mockContext).getDataSource("foo"); }) .withMessage("Unable to find jdbc/foo"); } ``` Class I'm trying to test: ``` public class DataSourceFactory { // Dependencies to be injected private InitialContext context; public DataSourceFactory(InitialContext context) throws ConnectionFactoryException { if(context == null) { throw new ConnectionFactoryException("context can't be null"); } this.context = context; } public DataSource getDataSource(String dataSourceName) throws ConnectionFactoryException { if(dataSourceName == null) { throw new ConnectionFactoryException("dataSourceName can't be null"); } // Ensure we have the correct syntax for the datasource name if(!dataSourceName.startsWith("jdbc/")) { dataSourceName = "jdbc/" + dataSourceName; } try { System.out.println("java:comp/env/" + dataSourceName); DataSource dataSource = (DataSource) context.lookup("java:comp/env/" + dataSourceName); return dataSource; } catch (NamingException e) { throw new ConnectionFactoryException("Unable to find " + dataSourceName, e); } } } ``` I know I've read that I shouldn't mock objects I don't own, but I can't figure out how to test the `getDataSource()` method without mocking `InitialContext`.