PackageLocator { public File locatePackage(final Class clazz) { if (clazz == null) { throw new IllegalArgumentException("clazz was null"); } File classFilePath = getClasspathFromProtectionDomain(clazz); if (classFilePath == null) { classFilePath = getClasspathFromResource(clazz); } return classFilePath; } PackageLocator();   PackageLocator(final ClassPropertyAccessor classPropertyAccessor); File locatePackage(final Class clazz);  }
@Test public void locatePackage_fallbackOnNullCodeSourceLocation() throws Exception { final URL url = new URL("jar:file:/abc/def.jar!/com/microsoft/alm/oauth2/useragent/utils/PackageLocatorTest.class"); final CodeSource codesource = new CodeSource(null, (Certificate[])null); final ProtectionDomain protectionDomain = new ProtectionDomain(codesource, null); when(classPropertyAccessorMock.getProtectionDomain(testClazz)).thenReturn(protectionDomain); when(classPropertyAccessorMock.getResource(testClazz, testClazz.getSimpleName() + ".class")).thenReturn(url); when(classPropertyAccessorMock.getCanonicalName(testClazz)).thenReturn(testClazz.getCanonicalName()); final File actual = underTest.locatePackage(testClazz); assertEquals("/abc/def.jar", actual); }
@Test public void locatePackage_fallbackToJarResourceOnSecurityException() throws Exception { final URL url = new URL("jar:file:/abc/def.jar!/com/microsoft/alm/oauth2/useragent/utils/PackageLocatorTest.class"); when(classPropertyAccessorMock.getProtectionDomain(testClazz)).thenThrow(new SecurityException()); when(classPropertyAccessorMock.getResource(testClazz, testClazz.getSimpleName() + ".class")).thenReturn(url); when(classPropertyAccessorMock.getCanonicalName(testClazz)).thenReturn(testClazz.getCanonicalName()); final File actual = underTest.locatePackage(testClazz); assertEquals("/abc/def.jar", actual); }
@Test public void locatePackage_fallbackToWindowsResourcePathOnSecurityException() throws Exception { final URL url = new URL("file:/E:/windowsPath/Test/com/microsoft/alm/oauth2/useragent/utils/PackageLocatorTest.class"); when(classPropertyAccessorMock.getProtectionDomain(testClazz)).thenThrow(new SecurityException()); when(classPropertyAccessorMock.getResource(testClazz, testClazz.getSimpleName() + ".class")).thenReturn(url); when(classPropertyAccessorMock.getCanonicalName(testClazz)).thenReturn(testClazz.getCanonicalName()); final File actual = underTest.locatePackage(testClazz); assertEquals("/E:/windowsPath/Test", actual); }
@Test public void locatePackage_favorProtectionDomain() throws Exception { when(classPropertyAccessorMock.getProtectionDomain(testClazz)).thenReturn(testClazz.getProtectionDomain()); when(classPropertyAccessorMock.getCanonicalName(testClazz)).thenReturn(testClazz.getCanonicalName()); final File actual = underTest.locatePackage(testClazz); Assert.assertTrue(actual.getAbsolutePath().endsWith("test-classes")); }