Catfish Catfish - 3 months ago 41
Java Question

Mockito Checked exception is invalid for this method

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

public void shouldThrowExceptionIfDataSourceDoesNotExist() throws ConnectionFactoryException {
.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
method without mocking


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`):

    .thenThrow(new NamingExcetpion("test"));