### Question:
JdbcRelationProvider implements RelationProvider { @Nonnull @Override public BaseRelation createRelation(@Nonnull final SQLContext sqlContext, @Nonnull final Map<String, String> parameters) { final RelationProvider provider = findProvider(); if (provider != null) { final BaseRelation relation = provider.createRelation(sqlContext, parameters); return new JdbcRelation(relation, Thread.currentThread().getContextClassLoader()); } else { throw new IllegalStateException("Cannot find Spark JDBC relation provider"); } }  @Nonnull @Override BaseRelation createRelation(@Nonnull final SQLContext sqlContext, @Nonnull final Map<String, String> parameters);  }### Answer:
@Test @SuppressWarnings("unchecked") public void testWithClassLoader() { final Map<String, String> parameters = (Map<String, String>) Map$.MODULE$.<String, String>newBuilder() .$plus$eq(new Tuple2<>("dbtable", "mytable")) .$plus$eq(new Tuple2<>("url", "jdbc:h2:mem:spark")) .result(); final DataSourceResourceLoader classLoader = new DataSourceResourceLoader(Mockito.mock(SparkContext.class), Thread.currentThread().getContextClassLoader()); final AtomicReference<JdbcRelation> relation = new AtomicReference<>(); classLoader.runWithThreadContext(new Runnable() { @Override public void run() { try (final Connection conn = DriverManager.getConnection("jdbc:h2:mem:spark"); final Statement stmt = conn.createStatement()) { stmt.execute("CREATE TABLE mytable (col1 VARCHAR)"); final JdbcRelationProvider provider = new JdbcRelationProvider(); relation.set((JdbcRelation) provider.createRelation(Mockito.mock(SQLContext.class), parameters)); } catch (final Exception e) { Throwables.propagate(e); } } }); Assert.assertNotNull("Expected relation to be created", relation.get()); Assert.assertEquals(JDBCRelation.class, relation.get().getDelegate().getClass()); Assert.assertEquals(classLoader, relation.get().getLoader()); }
@Test @SuppressWarnings("unchecked") public void testWithoutClassLoader() throws Exception { final Map<String, String> parameters = (Map<String, String>) Map$.MODULE$.<String, String>newBuilder() .$plus$eq(new Tuple2<>("dbtable", "mytable")) .$plus$eq(new Tuple2<>("url", "jdbc:h2:mem:spark")) .result(); try (final Connection conn = DriverManager.getConnection("jdbc:h2:mem:spark"); final Statement stmt = conn.createStatement()) { stmt.execute("CREATE TABLE mytable (col1 VARCHAR)"); final JdbcRelationProvider provider = new JdbcRelationProvider(); final JdbcRelation relation = (JdbcRelation) provider.createRelation(Mockito.mock(SQLContext.class), parameters); Assert.assertEquals(JDBCRelation.class, relation.getDelegate().getClass()); Assert.assertNull("Expected null class loader", relation.getLoader()); } }