1 package test.serviceloader;
2 
3 import java.net.MalformedURLException;
4 import java.net.URL;
5 import java.net.URLClassLoader;
6 
7 import org.testng.Assert;
8 import org.testng.TestNG;
9 import org.testng.annotations.Test;
10 
11 import test.SimpleBaseTest;
12 import test.listeners.ListenerAssert;
13 
14 public class ServiceLoaderTest extends SimpleBaseTest {
15 
16   @Test
serviceLoaderShouldWork()17   public void serviceLoaderShouldWork() throws MalformedURLException {
18     TestNG tng = create(ServiceLoaderSampleTest.class);
19     URL url = getClass().getClassLoader().getResource("serviceloader.jar");
20     URLClassLoader ucl = URLClassLoader.newInstance(new URL[] { url });
21     tng.setServiceLoaderClassLoader(ucl);
22     tng.run();
23 
24     ListenerAssert.assertListenerType(tng.getServiceLoaderListeners(), TmpSuiteListener.class);
25   }
26 
27   @Test
serviceLoaderWithNoClassLoader()28   public void serviceLoaderWithNoClassLoader() {
29     //Here ServiceLoader is expected to rely on the current context class loader to load the service loader file
30     //Since serviceloader.jar doesn't seem to be visible to the current thread's contextual class loader
31     //resorting to pushing in a class loader into the current thread that can load the resource
32     URL url = getClass().getClassLoader().getResource("serviceloader.jar");
33     URLClassLoader ucl = URLClassLoader.newInstance(new URL[] { url });
34     Thread.currentThread().setContextClassLoader(ucl);
35     TestNG tng = create(ServiceLoaderSampleTest.class);
36     tng.run();
37 
38     ListenerAssert.assertListenerType(tng.getServiceLoaderListeners(), TmpSuiteListener.class);
39   }
40 
41   @Test(description = "GITHUB-491")
serviceLoaderShouldWorkWithConfigurationListener()42   public void serviceLoaderShouldWorkWithConfigurationListener() {
43     TestNG tng = create(ServiceLoaderSampleTest.class);
44     tng.run();
45 
46     Assert.assertEquals(1, tng.getServiceLoaderListeners().size());
47     ListenerAssert.assertListenerType(tng.getServiceLoaderListeners(), MyConfigurationListener.class);
48   }
49 }
50