0

I am trying to migrate a library to java 10 but I have some errors regarding Mockito and Byte Buddy. Here is the piece of registration logic of

java.sql.Driver underlayingDriver = mock(java.sql.Driver.class);
underlayingDriver = mock(java.sql.Driver.class);
DriverManager.registerDriver(underlayingDriver);

and usage:

List<java.sql.Driver> driversInManager = Collections.list(DriverManager.getDrivers());

Problem is occurring in the internal part of JDK since it is trying to load class by classloader:

private static boolean isDriverAllowed(Driver driver, ClassLoader classLoader) {
    boolean result = false;
    if (driver != null) {
        Class<?> aClass = null;
        try {
            aClass =  Class.forName(driver.getClass().getName(), true, classLoader);
        } catch (Exception ex) {
            result = false;
        }

         result = ( aClass == driver.getClass() ) ? true : false;
    }

    return result;
}

Mocked class classloader is not same as the JUnits caller class.

How can I load correct driver from a different classloader?

Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192
Cemo
  • 5,370
  • 10
  • 50
  • 82
  • Probably Rafael you will land soon here. :) Here is the project for you: https://github.com/cemo/jdbcmetrics – Cemo Jun 03 '18 at 13:18

1 Answers1

0

The problem here is the class loader sensitivity of the driver manager. For java. classes, Mockito cannot inject mocks into the bootstrap loader but moves the mock classes into a different class loader as the mocks must be able to see the Mockito classes.

Maybe you can work around this by creating a pseudo driver class:

interface MyDriver extends java.sql.Driver {}

and create the mock of that class. This way, your class loader and that of the driver should be identical.

Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192