1package test.serviceloader;
2
3import java.net.MalformedURLException;
4import java.net.URL;
5import java.net.URLClassLoader;
6
7import org.testng.Assert;
8import org.testng.TestNG;
9import org.testng.annotations.Test;
10
11import test.SimpleBaseTest;
12import test.listeners.ListenerAssert;
13
14public class ServiceLoaderTest extends SimpleBaseTest {
15
16  @Test
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
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")
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