This is an automated email from the ASF dual-hosted git repository. alien11689 pushed a commit to branch remove-usage-of-deprecated-junit-3-api in repository https://gitbox.apache.org/repos/asf/aries.git
commit 4da99483e5b78c73cdb599cca5373603cfdaf46c Author: Dominik Przybysz <[email protected]> AuthorDate: Fri May 9 16:01:45 2025 +0200 [MAINTENANCE] Replace Assert.fail with assertThrows --- .../org/apache/aries/ant/taskdefs/EsaTaskTest.java | 65 +-- .../apache/aries/jmx/framework/FrameworkTest.java | 46 +- .../jmx/test/blueprint/BlueprintMBeanTest.java | 1 - .../aries/jmx/whiteboard/MBeanHolderTest.java | 9 +- .../aries/jndi/url/ServiceRegistryContextTest.java | 492 ++++++++++----------- proxy/proxy-impl/pom.xml | 1 + .../aries/blueprint/proxy/AbstractProxyTest.java | 38 +- .../blueprint/proxy/InterfaceProxyingTest.java | 14 +- .../blueprint/proxy/WovenProxyGeneratorTest.java | 32 +- proxy/proxy-itests/pom.xml | 1 + .../ClientWeavingHookGenericCapabilityTest.java | 20 +- subsystem/subsystem-core/pom.xml | 4 +- ...ndleRequiredExecutionEnvironmentHeaderTest.java | 9 +- .../core/archive/FragmentHostHeaderTest.java | 29 +- .../subsystem/core/archive/GenericHeaderTest.java | 29 +- .../subsystem/core/internal/LocationTest.java | 41 +- .../modelling/utils/DeployedBundlesTest.java | 146 +----- .../utils/PackageRequirementMergerTest.java | 24 +- transaction/transaction-blueprint/pom.xml | 4 +- .../apache/aries/transaction/TranStrategyTest.java | 79 +--- .../org/apache/aries/util/VersionRangeTest.java | 38 +- .../aries/util/filesystem/FileSystemTest.java | 9 +- .../apache/aries/util/filesystem/IOUtilsTest.java | 14 +- .../util/manifest/ManifestHeaderProcessorTest.java | 32 +- .../aries/versioning/tests/FilterResultsTest.java | 14 +- .../aries/web/converter/impl/WabConverterTest.java | 13 +- 26 files changed, 432 insertions(+), 772 deletions(-) diff --git a/esa-ant-task/src/test/java/org/apache/aries/ant/taskdefs/EsaTaskTest.java b/esa-ant-task/src/test/java/org/apache/aries/ant/taskdefs/EsaTaskTest.java index 8a115eea6..a4e7c4464 100755 --- a/esa-ant-task/src/test/java/org/apache/aries/ant/taskdefs/EsaTaskTest.java +++ b/esa-ant-task/src/test/java/org/apache/aries/ant/taskdefs/EsaTaskTest.java @@ -19,20 +19,19 @@ package org.apache.aries.ant.taskdefs; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.types.FileSet; +import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; -import org.apache.tools.ant.Project; -import org.apache.tools.ant.types.FileSet; -import org.junit.Test; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; /** * @version $Id: $ @@ -40,7 +39,7 @@ import org.junit.Test; public class EsaTaskTest { @Test - public void generateArchiveNoManifest() { + public void generateArchiveNoManifest() throws IOException { File srcDir = new File("../src/test/resources"); @@ -63,20 +62,15 @@ public class EsaTaskTest { esaTask.execute(); assertTrue(destfile.exists()); - try { - ZipFile esaArchive = new ZipFile(destfile); - assertNotNull(esaArchive); - ZipEntry subsystemManifest = - esaArchive.getEntry("OSGI-INF/SUBSYSTEM.MF"); - assertNull(subsystemManifest); - } - catch (IOException e) { - fail(e.getMessage()); - } + ZipFile esaArchive = new ZipFile(destfile); + assertNotNull(esaArchive); + ZipEntry subsystemManifest = + esaArchive.getEntry("OSGI-INF/SUBSYSTEM.MF"); + assertNull(subsystemManifest); } @Test - public void generateArchiveWithFileManifest() { + public void generateArchiveWithFileManifest() throws IOException { File srcDir = new File("../src/test/resources"); @@ -100,20 +94,15 @@ public class EsaTaskTest { esaTask.execute(); assertTrue(destfile.exists()); - try { - ZipFile esaArchive = new ZipFile(destfile); - assertNotNull(esaArchive); - ZipEntry subsystemManifest = - esaArchive.getEntry("OSGI-INF/SUBSYSTEM.MF"); - assertNotNull(subsystemManifest); - } - catch (IOException e) { - fail(e.getMessage()); - } + ZipFile esaArchive = new ZipFile(destfile); + assertNotNull(esaArchive); + ZipEntry subsystemManifest = + esaArchive.getEntry("OSGI-INF/SUBSYSTEM.MF"); + assertNotNull(subsystemManifest); } @Test - public void generateArchiveWithNewManifest() { + public void generateArchiveWithNewManifest() throws IOException { File srcDir = new File("../src/test/resources"); assertTrue(srcDir.exists()); @@ -145,15 +134,9 @@ public class EsaTaskTest { esaTask.execute(); assertTrue(destfile.exists()); - try { - ZipFile esaArchive = new ZipFile(destfile); - assertNotNull(esaArchive); - ZipEntry subsystemManifest = - esaArchive.getEntry("OSGI-INF/SUBSYSTEM.MF"); - assertNotNull(subsystemManifest); - } - catch (IOException e) { - fail(e.getMessage()); - } + ZipFile esaArchive = new ZipFile(destfile); + assertNotNull(esaArchive); + ZipEntry subsystemManifest = esaArchive.getEntry("OSGI-INF/SUBSYSTEM.MF"); + assertNotNull(subsystemManifest); } } diff --git a/jmx/jmx-core/src/test/java/org/apache/aries/jmx/framework/FrameworkTest.java b/jmx/jmx-core/src/test/java/org/apache/aries/jmx/framework/FrameworkTest.java index 0727683d4..bce7d2a78 100644 --- a/jmx/jmx-core/src/test/java/org/apache/aries/jmx/framework/FrameworkTest.java +++ b/jmx/jmx-core/src/test/java/org/apache/aries/jmx/framework/FrameworkTest.java @@ -39,8 +39,8 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * {@link FrameworkMBean} test case. @@ -89,12 +89,7 @@ public class FrameworkTest { Mockito.reset(context); Mockito.when(context.installBundle("file:test2.jar")).thenThrow(new BundleException("location doesn't exist")); - try { - mbean.installBundle("file:test2.jar"); - fail("Shouldn't go to this stage, location doesn't exist"); - } catch (IOException e) { - // ok - } + assertThrows(IOException.class, () -> mbean.installBundle("file:test2.jar")); } @@ -113,12 +108,7 @@ public class FrameworkTest { Mockito.when(context.installBundle(Mockito.anyString(), Mockito.any(InputStream.class))).thenThrow( new BundleException("location doesn't exist")); - try { - spiedMBean.installBundleFromURL("file:test2.jar", "test.jar"); - fail("Shouldn't go to this stage, location doesn't exist"); - } catch (IOException e) { - // ok - } + assertThrows(IOException.class, () -> spiedMBean.installBundleFromURL("file:test2.jar", "test.jar")); } @Test @@ -187,12 +177,7 @@ public class FrameworkTest { mbean.refreshBundle(1); Mockito.verify(admin).refreshPackages((Bundle[]) Mockito.any()); - try { - mbean.refreshBundle(2); - fail("IOException should be thrown"); - } catch (IOException e) { - // expected - } + assertThrows(IOException.class, () -> mbean.refreshBundle(2)); } @Test @@ -300,20 +285,11 @@ public class FrameworkTest { Mockito.when(context.getBundle(6)).thenReturn(bundle); Mockito.doThrow(new BundleException("")).when(bundle).start(); - try { - mbean.startBundle(6); - fail("Shouldn't go to this stage, BundleException was thrown"); - } catch (IOException ioe) { - // expected - } + assertThrows(IOException.class, () -> mbean.startBundle(6)); Mockito.when(context.getBundle(6)).thenReturn(null); - try { - mbean.startBundle(6); - fail("IOException should be thrown"); - } catch (IOException e) { - //expected - } + + assertThrows(IOException.class, () -> mbean.startBundle(6)); } @Test @@ -346,13 +322,7 @@ public class FrameworkTest { Mockito.verify(bundle).stop(); Mockito.when(context.getBundle(5)).thenReturn(null); - try { - mbean.stopBundle(5); - fail("IOException should be thrown"); - } catch (IOException e) { - //expected - } - + assertThrows(IOException.class, () -> mbean.startBundle(5)); } @Test diff --git a/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/BlueprintMBeanTest.java b/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/BlueprintMBeanTest.java index 54612a137..210612923 100644 --- a/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/BlueprintMBeanTest.java +++ b/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/BlueprintMBeanTest.java @@ -52,7 +52,6 @@ import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.util.Filter; import org.osgi.framework.Bundle; import org.osgi.framework.Constants; -import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.service.blueprint.container.BlueprintContainer; diff --git a/jmx/jmx-whiteboard/src/test/java/org/apache/aries/jmx/whiteboard/MBeanHolderTest.java b/jmx/jmx-whiteboard/src/test/java/org/apache/aries/jmx/whiteboard/MBeanHolderTest.java index 8f20110e1..46ddf07db 100644 --- a/jmx/jmx-whiteboard/src/test/java/org/apache/aries/jmx/whiteboard/MBeanHolderTest.java +++ b/jmx/jmx-whiteboard/src/test/java/org/apache/aries/jmx/whiteboard/MBeanHolderTest.java @@ -35,7 +35,7 @@ import org.mockito.stubbing.Answer; import org.slf4j.Logger; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; public class MBeanHolderTest { @Test @@ -117,12 +117,7 @@ public class MBeanHolderTest { thenThrow(new NullPointerException()); assertEquals(0, registrations.size()); - try { - mbh.register(ms, new String [] {}); - fail("Should have thrown a NullPointerException"); - } catch (NullPointerException npe) { - // good! - } + assertThrows(NullPointerException.class, () ->mbh.register(ms, new String [] {})); } private MBeanServer mockMBeanServer() diff --git a/jndi/jndi-url/src/test/java/org/apache/aries/jndi/url/ServiceRegistryContextTest.java b/jndi/jndi-url/src/test/java/org/apache/aries/jndi/url/ServiceRegistryContextTest.java index 24111f943..72ea06d81 100644 --- a/jndi/jndi-url/src/test/java/org/apache/aries/jndi/url/ServiceRegistryContextTest.java +++ b/jndi/jndi-url/src/test/java/org/apache/aries/jndi/url/ServiceRegistryContextTest.java @@ -18,32 +18,6 @@ */ package org.apache.aries.jndi.url; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.sql.SQLException; -import java.util.Collection; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.Properties; -import java.util.concurrent.Callable; - -import javax.naming.Binding; -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.naming.NameClassPair; -import javax.naming.NameNotFoundException; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.spi.ObjectFactory; -import javax.sql.DataSource; - import org.apache.aries.jndi.api.JNDIConstants; import org.apache.aries.mocks.BundleContextMock; import org.apache.aries.mocks.BundleMock; @@ -62,6 +36,31 @@ import org.osgi.framework.ServiceFactory; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; +import javax.naming.Binding; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NameClassPair; +import javax.naming.NameNotFoundException; +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; +import javax.naming.spi.ObjectFactory; +import javax.sql.DataSource; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.sql.SQLException; +import java.util.Collection; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.Properties; +import java.util.concurrent.Callable; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + /** * Tests for our JNDI implementation for the service registry. */ @@ -73,14 +72,14 @@ public class ServiceRegistryContextTest private BundleContext bc; /** The service registration for the service */ private ServiceRegistration reg; - + /** * This method does the setup to ensure we always have a service. - * @throws NamingException - * @throws NoSuchFieldException - * @throws SecurityException - * @throws IllegalAccessException - * @throws IllegalArgumentException + * @throws NamingException + * @throws NoSuchFieldException + * @throws SecurityException + * @throws IllegalAccessException + * @throws IllegalArgumentException */ @Before public void registerService() throws Exception @@ -89,67 +88,67 @@ public class ServiceRegistryContextTest registerProxyManager(); new org.apache.aries.jndi.startup.Activator().start(bc); new Activator().start(bc); - + service = Skeleton.newMock(Runnable.class); - + registerService(service); } - - private void registerProxyManager() + + private void registerProxyManager() { ProxyManager mgr = Skeleton.newMock(ProxyManager.class); - + // public Object createDelegatingProxy(Bundle clientBundle, Collection<Class<?>> classes, Callable<Object> dispatcher, Object template) throws UnableToProxyException; Skeleton.getSkeleton(mgr).registerMethodCallHandler(new MethodCall(ProxyManager.class, "createDelegatingProxy", Bundle.class, Collection.class, Callable.class, Object.class), - new MethodCallHandler() + new MethodCallHandler() { - public Object handle(MethodCall methodCall, Skeleton skeleton) throws Exception + public Object handle(MethodCall methodCall, Skeleton skeleton) throws Exception { @SuppressWarnings("unchecked") Collection<Class<?>> interfaceClasses = (Collection<Class<?>>) methodCall.getArguments()[1]; Class<?>[] classes = new Class<?>[interfaceClasses.size()]; - - Iterator<Class<?>> it = interfaceClasses.iterator(); + + Iterator<Class<?>> it = interfaceClasses.iterator(); for (int i = 0; it.hasNext(); i++) { classes[i] = it.next(); } - + @SuppressWarnings("unchecked") final Callable<Object> target = (Callable<Object>) methodCall.getArguments()[2]; - - return Proxy.newProxyInstance(this.getClass().getClassLoader(), classes, new InvocationHandler() + + return Proxy.newProxyInstance(this.getClass().getClassLoader(), classes, new InvocationHandler() { public Object invoke(Object mock, Method method, Object[] arguments) - throws Throwable + throws Throwable { return method.invoke(target.call(), arguments); } }); } }); - + bc.registerService(ProxyManager.class.getName(), mgr, null); } /** * Register a service in our map. - * + * * @param service2 The service to register. */ private void registerService(Runnable service2) { ServiceFactory factory = Skeleton.newMock(ServiceFactory.class); Skeleton skel = Skeleton.getSkeleton(factory); - + skel.setReturnValue(new MethodCall(ServiceFactory.class, "getService", Bundle.class, ServiceRegistration.class), service2); - + Hashtable<String, String> props = new Hashtable<String, String>(); props.put("rubbish", "smelly"); - + reg = bc.registerService(new String[] {"java.lang.Runnable"}, factory, props); } - + /** * Make sure we clear the caches out before the next test. */ @@ -157,61 +156,57 @@ public class ServiceRegistryContextTest public void teardown() { BundleContextMock.clear(); - + Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); } - + @Test public void testBaseLookup() throws NamingException { BundleMock mock = new BundleMock("scooby.doo", new Properties()); - + Thread.currentThread().setContextClassLoader(mock.getClassLoader()); InitialContext ctx = new InitialContext(); - + Context ctx2 = (Context) ctx.lookup("osgi:service"); - - Runnable r1 = (Runnable) ctx2.lookup("java.lang.Runnable"); + + Runnable r1 = (Runnable) ctx2.lookup("java.lang.Runnable"); assertNotNull(r1); assertTrue("expected proxied service class", r1 != service); - + Runnable r2 = (Runnable) ctx.lookup("aries:services/java.lang.Runnable"); assertNotNull(r2); assertTrue("expected non-proxied service class", r2 == service); } - + @Test public void testLookupWithPause() throws NamingException { BundleMock mock = new BundleMock("scooby.doo", new Properties()); - + Thread.currentThread().setContextClassLoader(mock.getClassLoader()); Hashtable<Object, Object> env = new Hashtable<Object, Object>(); env.put(JNDIConstants.REBIND_TIMEOUT, 1000); - + InitialContext ctx = new InitialContext(env); - + Context ctx2 = (Context) ctx.lookup("osgi:service"); - - Runnable r1 = (Runnable) ctx2.lookup("java.lang.Runnable"); - + + Runnable r1 = (Runnable) ctx2.lookup("java.lang.Runnable"); + reg.unregister(); - + long startTime = System.currentTimeMillis(); - - try { - r1.run(); - fail("Should have received an exception"); - } catch (ServiceException e) { - long endTime = System.currentTimeMillis(); - long diff = endTime - startTime; - - assertTrue("The run method did not fail in the expected time (1s): " + diff, diff >= 1000); - } + + assertThrows(ServiceException.class, () -> r1.run() ); + long endTime = System.currentTimeMillis(); + long diff = endTime - startTime; + + assertTrue("The run method did not fail in the expected time (1s): " + diff, diff >= 1000); } - + /** * This test checks that we correctly register and deregister the url context * object factory in the service registry. @@ -220,49 +215,49 @@ public class ServiceRegistryContextTest public void testJNDIRegistration() { ServiceReference ref = bc.getServiceReference(ObjectFactory.class.getName()); - + assertNotNull("The aries url context object factory was not registered", ref); - + ObjectFactory factory = (ObjectFactory) bc.getService(ref); - + assertNotNull("The aries url context object factory was null", factory); } - + @Test public void jndiLookupServiceNameTest() throws NamingException, SQLException { InitialContext ctx = new InitialContext(new Hashtable<Object, Object>()); - + BundleMock mock = new BundleMock("scooby.doo", new Properties()); - + Thread.currentThread().setContextClassLoader(mock.getClassLoader()); - + DataSource first = Skeleton.newMock(DataSource.class); DataSource second = Skeleton.newMock(DataSource.class); - + Hashtable<String, String> properties = new Hashtable<String, String>(); properties.put("osgi.jndi.service.name", "jdbc/myDataSource"); - + bc.registerService(DataSource.class.getName(), first, properties); properties = new Hashtable<String, String>(); properties.put("osgi.jndi.service.name", "jdbc/myDataSource2"); - + bc.registerService(DataSource.class.getName(), second, properties); - + DataSource s = (DataSource) ctx.lookup("osgi:service/jdbc/myDataSource"); - + assertNotNull(s); - + s = (DataSource) ctx.lookup("osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/myDataSource2)"); - + assertNotNull(s); - + s.isWrapperFor(DataSource.class); // don't care about the method, just need to call something. - + Skeleton.getSkeleton(second).assertCalled(new MethodCall(DataSource.class, "isWrapperFor", Class.class)); } - + /** * This test does a simple JNDI lookup to prove that works. * @throws NamingException @@ -271,45 +266,45 @@ public class ServiceRegistryContextTest public void simpleJNDILookup() throws NamingException { System.setProperty(Context.URL_PKG_PREFIXES, "helloMatey"); - + InitialContext ctx = new InitialContext(new Hashtable<Object, Object>()); - + BundleMock mock = new BundleMock("scooby.doo.1", new Properties()); - + Thread.currentThread().setContextClassLoader(mock.getClassLoader()); - + Runnable s = (Runnable) ctx.lookup("osgi:service/java.lang.Runnable"); - + assertNotNull("We didn't get a service back from our lookup :(", s); - + s.run(); - + Skeleton.getSkeleton(service).assertCalledExactNumberOfTimes(new MethodCall(Runnable.class, "run"), 1); - + Skeleton skel = Skeleton.getSkeleton(mock.getBundleContext()); - + skel.assertCalled(new MethodCall(BundleContext.class, "getServiceReferences", "java.lang.Runnable", null)); ctx = new InitialContext(new Hashtable<Object, Object>()); - + mock = new BundleMock("scooby.doo.2", new Properties()); - + Thread.currentThread().setContextClassLoader(mock.getClassLoader()); s = (Runnable) ctx.lookup("osgi:service/java.lang.Runnable"); - + // Check we have the packages set correctly - + String packages = System.getProperty(Context.URL_PKG_PREFIXES, null); - + assertTrue(ctx.getEnvironment().containsValue(packages)); assertNotNull("We didn't get a service back from our lookup :(", s); s.run(); - + Skeleton.getSkeleton(service).assertCalledExactNumberOfTimes(new MethodCall(Runnable.class, "run"), 2); - + skel = Skeleton.getSkeleton(mock.getBundleContext()); skel.assertCalled(new MethodCall(BundleContext.class, "getServiceReferences", "java.lang.Runnable", null)); } @@ -319,33 +314,33 @@ public class ServiceRegistryContextTest * Right now our mock service registry does not implement filtering, so the * effect is the same as simpleJNDILookup, but we at least know it is not * blowing up. - * + * * @throws NamingException */ @Test public void jndiLookupWithFilter() throws NamingException { BundleMock mock = new BundleMock("scooby.doo", new Properties()); - + Thread.currentThread().setContextClassLoader(mock.getClassLoader()); InitialContext ctx = new InitialContext(); - + Object s = ctx.lookup("osgi:service/java.lang.Runnable/(rubbish=smelly)"); - + assertNotNull("We didn't get a service back from our lookup :(", s); - + service.run(); - + Skeleton.getSkeleton(service).assertCalledExactNumberOfTimes(new MethodCall(Runnable.class, "run"), 1); Skeleton.getSkeleton(mock.getBundleContext()).assertCalled(new MethodCall(BundleContext.class, "getServiceReferences", "java.lang.Runnable", "(rubbish=smelly)")); } - + /** * Check that we get a NameNotFoundException if we lookup after the service * has been unregistered. - * + * * @throws NamingException */ @Test(expected=NameNotFoundException.class) @@ -354,58 +349,58 @@ public class ServiceRegistryContextTest reg.unregister(); BundleMock mock = new BundleMock("scooby.doo", new Properties()); - + Thread.currentThread().setContextClassLoader(mock.getClassLoader()); InitialContext ctx = new InitialContext(); - + ctx.lookup("osgi:service/java.lang.Runnable"); } - + /** * Check that we get a NameNotFoundException if we lookup something not in the * registry. - * + * * @throws NamingException */ @Test(expected=NameNotFoundException.class) public void testLookupForServiceWeNeverHad() throws NamingException { BundleMock mock = new BundleMock("scooby.doo", new Properties()); - + Thread.currentThread().setContextClassLoader(mock.getClassLoader()); InitialContext ctx = new InitialContext(); - + ctx.lookup("osgi:service/java.lang.Integer"); } - + /** * This test checks that we can list the contents of the repository using the * list method - * + * * @throws NamingException */ public void listRepositoryContents() throws NamingException { InitialContext ctx = new InitialContext(); - + NamingEnumeration<NameClassPair> serviceList = ctx.list("osgi:service/java.lang.Runnable/(rubbish=smelly)"); - + checkThreadRetrievedViaListMethod(serviceList); - + assertFalse("The repository contained more objects than we expected", serviceList.hasMoreElements()); - + //Now add a second service - + registerService(new Thread()); - + serviceList = ctx.list("osgi:service/java.lang.Runnable/(rubbish=smelly)"); - + checkThreadRetrievedViaListMethod(serviceList); - + checkThreadRetrievedViaListMethod(serviceList); - + assertFalse("The repository contained more objects than we expected", serviceList.hasMoreElements()); } @@ -413,115 +408,108 @@ public class ServiceRegistryContextTest public void checkProxyDynamism() throws NamingException { BundleMock mock = new BundleMock("scooby.doo", new Properties()); - + Thread.currentThread().setContextClassLoader(mock.getClassLoader()); InitialContext ctx = new InitialContext(); - + String className = Runnable.class.getName(); - + Runnable t = Skeleton.newMock(Runnable.class); Runnable t2 = Skeleton.newMock(Runnable.class); - + // we don't want the default service reg.unregister(); - + ServiceRegistration reg = bc.registerService(className, t, null); bc.registerService(className, t2, null); - + Runnable r = (Runnable) ctx.lookup("osgi:service/java.lang.Runnable"); - + r.run(); - + Skeleton.getSkeleton(t).assertCalledExactNumberOfTimes(new MethodCall(Runnable.class, "run"), 1); Skeleton.getSkeleton(t2).assertNotCalled(new MethodCall(Runnable.class, "run")); - + reg.unregister(); - + r.run(); - + Skeleton.getSkeleton(t).assertCalledExactNumberOfTimes(new MethodCall(Runnable.class, "run"), 1); Skeleton.getSkeleton(t2).assertCalledExactNumberOfTimes(new MethodCall(Runnable.class, "run"), 1); } - + @Test public void checkServiceListLookup() throws NamingException { BundleMock mock = new BundleMock("scooby.doo", new Properties()); - + Thread.currentThread().setContextClassLoader(mock.getClassLoader()); InitialContext ctx = new InitialContext(); - + String className = Runnable.class.getName(); - + Runnable t = Skeleton.newMock(Runnable.class); - + // we don't want the default service reg.unregister(); - + ServiceRegistration reg = bc.registerService(className, t, null); ServiceRegistration reg2 = bc.registerService("java.lang.Thread", new Thread(), null); - + Context ctx2 = (Context) ctx.lookup("osgi:servicelist/java.lang.Runnable"); - + Runnable r = (Runnable) ctx2.lookup(String.valueOf(reg.getReference().getProperty(Constants.SERVICE_ID))); r.run(); - + Skeleton.getSkeleton(t).assertCalled(new MethodCall(Runnable.class, "run")); - + reg.unregister(); - - try { - r.run(); - fail("Should have received a ServiceException"); - } catch (ServiceException e) { - assertEquals("service exception has the wrong type", ServiceException.UNREGISTERED, e.getType()); - } - - try { - ctx2.lookup(String.valueOf(reg2.getReference().getProperty(Constants.SERVICE_ID))); - fail("Expected a NameNotFoundException"); - } catch (NameNotFoundException e) { - } + + ServiceException e = assertThrows(ServiceException.class, () -> r.run()); + assertEquals("service exception has the wrong type", ServiceException.UNREGISTERED, e.getType()); + + assertThrows(NameNotFoundException.class, () -> + ctx2.lookup(String.valueOf(reg2.getReference().getProperty(Constants.SERVICE_ID)))); } - + @Test public void checkServiceListList() throws NamingException { BundleMock mock = new BundleMock("scooby.doo", new Properties()); - + Thread.currentThread().setContextClassLoader(mock.getClassLoader()); InitialContext ctx = new InitialContext(); - + String className = Runnable.class.getName(); - + Runnable t = Skeleton.newMock(Runnable.class); - + // we don't want the default service reg.unregister(); - + ServiceRegistration reg = bc.registerService(className, t, null); ServiceRegistration reg2 = bc.registerService(className, new Thread(), null); - + NamingEnumeration<NameClassPair> ne = ctx.list("osgi:servicelist/" + className); - + assertTrue(ne.hasMoreElements()); - + NameClassPair ncp = ne.nextElement(); - + assertEquals(String.valueOf(reg.getReference().getProperty(Constants.SERVICE_ID)), ncp.getName()); assertTrue("Class name not correct. Was: " + ncp.getClassName(), ncp.getClassName().contains("Proxy")); - + assertTrue(ne.hasMoreElements()); - + ncp = ne.nextElement(); - + assertEquals(String.valueOf(reg2.getReference().getProperty(Constants.SERVICE_ID)), ncp.getName()); assertEquals("Class name not correct.", Thread.class.getName(), ncp.getClassName()); - + assertFalse(ne.hasMoreElements()); } @@ -529,58 +517,58 @@ public class ServiceRegistryContextTest public void checkServiceListListBindings() throws NamingException { BundleMock mock = new BundleMock("scooby.doo", new Properties()); - + Thread.currentThread().setContextClassLoader(mock.getClassLoader()); InitialContext ctx = new InitialContext(); - + String className = Runnable.class.getName(); - + MethodCall run = new MethodCall(Runnable.class, "run"); - + Runnable t = Skeleton.newMock(Runnable.class); Runnable t2 = Skeleton.newMock(Runnable.class); - + // we don't want the default service reg.unregister(); - + ServiceRegistration reg = bc.registerService(className, t, null); ServiceRegistration reg2 = bc.registerService(className, t2, null); - + NamingEnumeration<Binding> ne = ctx.listBindings("osgi:servicelist/" + className); - + assertTrue(ne.hasMoreElements()); - + Binding bnd = ne.nextElement(); - + assertEquals(String.valueOf(reg.getReference().getProperty(Constants.SERVICE_ID)), bnd.getName()); assertTrue("Class name not correct. Was: " + bnd.getClassName(), bnd.getClassName().contains("Proxy") || bnd.getClassName().contains("EnhancerByCGLIB")); - + Runnable r = (Runnable) bnd.getObject(); - + assertNotNull(r); - + r.run(); - + Skeleton.getSkeleton(t).assertCalledExactNumberOfTimes(run, 1); Skeleton.getSkeleton(t2).assertNotCalled(run); - + assertTrue(ne.hasMoreElements()); - + bnd = ne.nextElement(); - + assertEquals(String.valueOf(reg2.getReference().getProperty(Constants.SERVICE_ID)), bnd.getName()); assertTrue("Class name not correct. Was: " + bnd.getClassName(), bnd.getClassName().contains("Proxy") || bnd.getClassName().contains("EnhancerByCGLIB")); - + r = (Runnable) bnd.getObject(); - + assertNotNull(r); - + r.run(); - + Skeleton.getSkeleton(t).assertCalledExactNumberOfTimes(run, 1); Skeleton.getSkeleton(t2).assertCalledExactNumberOfTimes(run, 1); - + assertFalse(ne.hasMoreElements()); } @@ -588,69 +576,69 @@ public class ServiceRegistryContextTest public void checkProxyWhenServiceGoes() throws ServiceException, NamingException { BundleMock mock = new BundleMock("scooby.doo", new Properties()); - + Thread.currentThread().setContextClassLoader(mock.getClassLoader()); InitialContext ctx = new InitialContext(); - + Runnable r = (Runnable) ctx.lookup("osgi:service/java.lang.Runnable"); - + r.run(); - + Skeleton.getSkeleton(service).assertCalled(new MethodCall(Runnable.class, "run")); - + reg.unregister(); - + r.run(); } - + @Test public void checkServiceOrderObserved() throws NamingException { BundleMock mock = new BundleMock("scooby.doo", new Properties()); - + Thread.currentThread().setContextClassLoader(mock.getClassLoader()); InitialContext ctx = new InitialContext(); - + String className = Runnable.class.getName(); - + Runnable t = Skeleton.newMock(Runnable.class); Runnable t2 = Skeleton.newMock(Runnable.class); - + // we don't want the default service reg.unregister(); - + ServiceRegistration reg = bc.registerService(className, t, null); ServiceRegistration reg2 = bc.registerService(className, t2, null); - + Runnable r = (Runnable) ctx.lookup("osgi:service/java.lang.Runnable"); - + r.run(); - + Skeleton.getSkeleton(t).assertCalledExactNumberOfTimes(new MethodCall(Runnable.class, "run"), 1); Skeleton.getSkeleton(t2).assertNotCalled(new MethodCall(Runnable.class, "run")); - + reg.unregister(); reg2.unregister(); - + Hashtable<String, Object> props = new Hashtable<String, Object>(); props.put(Constants.SERVICE_RANKING, 55); - + t = Skeleton.newMock(Runnable.class); t2 = Skeleton.newMock(Runnable.class); bc.registerService(className, t, null); bc.registerService(className, t2, props); - + r = (Runnable) ctx.lookup("osgi:service/java.lang.Runnable"); - + r.run(); - + Skeleton.getSkeleton(t).assertNotCalled(new MethodCall(Runnable.class, "run")); Skeleton.getSkeleton(t2).assertCalledExactNumberOfTimes(new MethodCall(Runnable.class, "run"), 1); } - + /** * Check that the NamingEnumeration passed in has another element, which represents a java.lang.Thread * @param serviceList @@ -660,50 +648,50 @@ public class ServiceRegistryContextTest throws NamingException { assertTrue("The repository was empty", serviceList.hasMoreElements()); - + NameClassPair ncp = serviceList.next(); - + assertNotNull("We didn't get a service back from our lookup :(", ncp); - + assertNotNull("The object from the SR was null", ncp.getClassName()); - + assertEquals("The service retrieved was not of the correct type", "java.lang.Thread", ncp.getClassName()); - + assertEquals("osgi:service/java.lang.Runnable/(rubbish=smelly)", ncp.getName().toString()); } - + /** * This test checks that we can list the contents of the repository using the * list method - * + * * @throws NamingException */ public void listRepositoryBindings() throws NamingException { InitialContext ctx = new InitialContext(); - + NamingEnumeration<Binding> serviceList = ctx.listBindings("osgi:service/java.lang.Runnable/(rubbish=smelly)"); - + Object returnedService = checkThreadRetrievedViaListBindingsMethod(serviceList); - + assertFalse("The repository contained more objects than we expected", serviceList.hasMoreElements()); - + assertTrue("The returned service was not the service we expected", returnedService == service); - + //Now add a second service Thread secondService = new Thread(); registerService(secondService); - + serviceList = ctx.listBindings("osgi:service/java.lang.Runnable/(rubbish=smelly)"); - + Object returnedService1 = checkThreadRetrievedViaListBindingsMethod(serviceList); - + Object returnedService2 = checkThreadRetrievedViaListBindingsMethod(serviceList); - + assertFalse("The repository contained more objects than we expected", serviceList.hasMoreElements()); - + assertTrue("The services were not the ones we expected!",(returnedService1 == service || returnedService2 == service) && (returnedService1 == secondService || returnedService2 == secondService) && (returnedService1 != returnedService2)); - + } /** @@ -716,18 +704,18 @@ public class ServiceRegistryContextTest throws NamingException { assertTrue("The repository was empty", serviceList.hasMoreElements()); - + Binding binding = serviceList.nextElement(); - + assertNotNull("We didn't get a service back from our lookup :(", binding); - + assertNotNull("The object from the SR was null", binding.getObject()); - + assertTrue("The service retrieved was not of the correct type", binding.getObject() instanceof Thread); - + assertEquals("osgi:service/java.lang.Runnable/(rubbish=smelly)", binding.getName().toString()); - + return binding.getObject(); } - + } \ No newline at end of file diff --git a/proxy/proxy-impl/pom.xml b/proxy/proxy-impl/pom.xml index f0f4eff34..452530a06 100644 --- a/proxy/proxy-impl/pom.xml +++ b/proxy/proxy-impl/pom.xml @@ -69,6 +69,7 @@ <commons-io.version>2.19.0</commons-io.version> <geronimo-j2ee-connector_1.6_spec.version>1.0</geronimo-j2ee-connector_1.6_spec.version> <javax.transaction-api.version>1.3</javax.transaction-api.version> + <junit.version>4.13.2</junit.version> <mockito-core.version>4.11.0</mockito-core.version> <org.apache.aries.proxy.api.version>1.1.1</org.apache.aries.proxy.api.version> <osgi.cmpn.version>4.3.1</osgi.cmpn.version> diff --git a/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/AbstractProxyTest.java b/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/AbstractProxyTest.java index a8c55c4ca..b0f4da05b 100644 --- a/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/AbstractProxyTest.java +++ b/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/AbstractProxyTest.java @@ -18,18 +18,6 @@ */ package org.apache.aries.blueprint.proxy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.concurrent.Callable; - import org.apache.aries.blueprint.proxy.ProxyTestClassInnerClasses.ProxyTestClassInner; import org.apache.aries.blueprint.proxy.ProxyTestClassInnerClasses.ProxyTestClassStaticInner; import org.apache.aries.proxy.InvocationListener; @@ -37,6 +25,18 @@ import org.apache.aries.proxy.impl.SingleInstanceDispatcher; import org.junit.Test; import org.osgi.framework.wiring.BundleWiring; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.concurrent.Callable; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + public abstract class AbstractProxyTest { protected static class TestListener implements InvocationListener { @@ -323,14 +323,14 @@ public abstract class AbstractProxyTest { assertCalled(tl, false, false, false); m = getDeclaredMethod(getTestClass(), "testException", new Class[] {}); - try { - m.invoke(obj); - fail("Should throw an exception"); - } catch (InvocationTargetException re) { - if(!re.getTargetException().getClass().equals(RuntimeException.class)) - throw re.getTargetException(); + + Method finalM = m; + InvocationTargetException re = assertThrows(InvocationTargetException.class, + () -> finalM.invoke(obj)); + if (!re.getTargetException().getClass().equals(RuntimeException.class)) + throw re.getTargetException(); assertCalled(tl, true, false, true); - } + tl.clear(); assertCalled(tl, false, false, false); diff --git a/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/InterfaceProxyingTest.java b/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/InterfaceProxyingTest.java index 98740a10c..0c7c0f8e4 100644 --- a/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/InterfaceProxyingTest.java +++ b/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/InterfaceProxyingTest.java @@ -22,8 +22,8 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -135,14 +135,10 @@ public class InterfaceProxyingTest { throw new RuntimeException(); } }); - try { - o.call(); - fail("Should throw an exception"); - } catch (RuntimeException re) { - assertCalled(tl, true, false, true); - assertSame(re, tl.getLastThrowable()); - } - + RuntimeException re = assertThrows(RuntimeException.class, () -> o.call()); + assertCalled(tl, true, false, true); + assertSame(re, tl.getLastThrowable()); + tl.clear(); assertCalled(tl, false, false, false); diff --git a/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/WovenProxyGeneratorTest.java b/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/WovenProxyGeneratorTest.java index be9043705..5e1d08a88 100644 --- a/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/WovenProxyGeneratorTest.java +++ b/proxy/proxy-impl/src/test/java/org/apache/aries/blueprint/proxy/WovenProxyGeneratorTest.java @@ -21,8 +21,8 @@ package org.apache.aries.blueprint.proxy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -294,14 +294,11 @@ public class WovenProxyGeneratorTest extends AbstractProxyTest @Test public void testUnweavableSuperWithNoNoargsAllTheWay() throws Exception { - try { - getProxyClass(ProxyTestClassUnweavableSibling.class); - fail(); - } catch (RuntimeException re) { + RuntimeException re = assertThrows(RuntimeException.class, () -> + getProxyClass(ProxyTestClassUnweavableSibling.class)); assertTrue(re.getCause() instanceof UnableToProxyException); assertEquals(ProxyTestClassUnweavableSibling.class.getName(), ((UnableToProxyException)re.getCause()).getClassName()); - } } /** @@ -310,16 +307,15 @@ public class WovenProxyGeneratorTest extends AbstractProxyTest @Test public void testUnweavableSuperWithFinalMethod() throws Exception { - try{ - getProxyClass(ProxyTestClassUnweavableChildWithFinalMethodParent.class); - fail(); - } catch (RuntimeException re) { + RuntimeException re = assertThrows(RuntimeException.class, () -> { + getProxyClass(ProxyTestClassUnweavableChildWithFinalMethodParent.class); + }); + assertTrue(re.getCause() instanceof FinalModifierException); assertEquals(ProxyTestClassUnweavableSuperWithFinalMethod.class.getName(), ((FinalModifierException)re.getCause()).getClassName()); assertEquals("doStuff2", ((FinalModifierException)re.getCause()) .getFinalMethods()); - } } /** @@ -328,28 +324,24 @@ public class WovenProxyGeneratorTest extends AbstractProxyTest @Test public void testUnweavableSuperWithDefaultMethodInWrongPackage() throws Exception { - try{ - getProxyClass(ProxyTestClassUnweavableChildWithDefaultMethodWrongPackageParent.class); - fail(); - } catch (RuntimeException re) { + RuntimeException re = assertThrows(RuntimeException.class, () -> { + getProxyClass(ProxyTestClassUnweavableChildWithDefaultMethodWrongPackageParent.class); + }); assertTrue(re.getCause() instanceof UnableToProxyException); assertEquals(ProxyTestClassUnweavableSuperWithDefaultMethodWrongPackageParent .class.getName(), ((UnableToProxyException)re.getCause()).getClassName()); - } } @Test public void testInnerWithNoParentNoArgs() throws Exception { //An inner class has no no-args (the parent gets added as an arg) so we can't //get an instance - try{ + RuntimeException re = assertThrows(RuntimeException.class, () -> { getProxyClass(ProxyTestClassUnweavableInnerChild.class); - fail(); - } catch (RuntimeException re) { + }); assertTrue(re.getCause() instanceof UnableToProxyException); assertEquals(ProxyTestClassUnweavableInnerChild.class.getName(), ((UnableToProxyException)re.getCause()).getClassName()); - } } @Test(expected=NoSuchFieldException.class) diff --git a/proxy/proxy-itests/pom.xml b/proxy/proxy-itests/pom.xml index 5bb430879..2fc6d5344 100644 --- a/proxy/proxy-itests/pom.xml +++ b/proxy/proxy-itests/pom.xml @@ -130,6 +130,7 @@ <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> + <version>4.13.2</version> <scope>test</scope> </dependency> diff --git a/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/ClientWeavingHookGenericCapabilityTest.java b/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/ClientWeavingHookGenericCapabilityTest.java index 8d7895129..1b3be75c0 100644 --- a/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/ClientWeavingHookGenericCapabilityTest.java +++ b/spi-fly/spi-fly-dynamic-bundle/src/test/java/org/apache/aries/spifly/dynamic/ClientWeavingHookGenericCapabilityTest.java @@ -67,8 +67,8 @@ import aQute.bnd.header.Parameters; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; public class ClientWeavingHookGenericCapabilityTest { DynamicWeavingActivator activator; @@ -317,17 +317,13 @@ public class ClientWeavingHookGenericCapabilityTest { // Invoke the woven class, check that it properly set the TCCL so that the implementation of impl5 is called. // That implementation throws an exception, after which we are making sure that the TCCL is set back appropriately. - try { - method.invoke(cls.getDeclaredConstructor().newInstance(), "hello"); - fail("Invocation should have thrown an exception"); - } catch (InvocationTargetException ite) { - RuntimeException re = (RuntimeException) ite.getCause(); - String msg = re.getMessage(); - assertEquals("Uh-oh: hello", msg); - - // The TCCL should have been reset correctly - assertSame(cl, Thread.currentThread().getContextClassLoader()); - } + InvocationTargetException ite = assertThrows(InvocationTargetException.class, () -> method.invoke(cls.getDeclaredConstructor().newInstance(), "hello")); + RuntimeException re = (RuntimeException) ite.getCause(); + String msg = re.getMessage(); + assertEquals("Uh-oh: hello", msg); + + // The TCCL should have been reset correctly + assertSame(cl, Thread.currentThread().getContextClassLoader()); } @Test diff --git a/subsystem/subsystem-core/pom.xml b/subsystem/subsystem-core/pom.xml index b410f3211..3a1ef17e9 100644 --- a/subsystem/subsystem-core/pom.xml +++ b/subsystem/subsystem-core/pom.xml @@ -24,7 +24,7 @@ <parent> <groupId>org.apache.aries</groupId> <artifactId>parent</artifactId> - <version>2.0.0</version> + <version>2.1.1</version> <relativePath>../../parent/pom.xml</relativePath> </parent> @@ -66,7 +66,7 @@ uses:="org.osgi.service.subsystem,org.apache.aries.subsystem" </aries.osgi.provide.capability> - + <junit.version>4.13.2</junit.version> <org.apache.aries.subsystem.api.version>2.0.10</org.apache.aries.subsystem.api.version> <org.apache.aries.util.version>2.0.0-SNAPSHOT</org.apache.aries.util.version> <org.apache.aries.subsystem.modeller.version>1.0.0-SNAPSHOT</org.apache.aries.subsystem.modeller.version> diff --git a/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/archive/BundleRequiredExecutionEnvironmentHeaderTest.java b/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/archive/BundleRequiredExecutionEnvironmentHeaderTest.java index 63df07de0..cb52a60ce 100644 --- a/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/archive/BundleRequiredExecutionEnvironmentHeaderTest.java +++ b/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/archive/BundleRequiredExecutionEnvironmentHeaderTest.java @@ -16,7 +16,6 @@ package org.apache.aries.subsystem.core.archive; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import java.util.List; @@ -190,13 +189,7 @@ public class BundleRequiredExecutionEnvironmentHeaderTest { } private void doTestParser(String clause, String name, Version version) { - ExecutionEnvironment ee = null; - try { - ee = new Parser().parse(clause); - } - catch (Exception e) { - fail("Unable to parse execution environment from clause " + clause); - } + ExecutionEnvironment ee = new Parser().parse(clause); assertExecutionEnvironmentName(ee, name); assertExecutionEnvironmentVersion(ee, version); } diff --git a/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/archive/FragmentHostHeaderTest.java b/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/archive/FragmentHostHeaderTest.java index 9feb8050c..3b11c6c9e 100644 --- a/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/archive/FragmentHostHeaderTest.java +++ b/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/archive/FragmentHostHeaderTest.java @@ -19,7 +19,7 @@ package org.apache.aries.subsystem.core.archive; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; import org.junit.Test; import org.osgi.framework.Version; @@ -29,40 +29,19 @@ public class FragmentHostHeaderTest { @Test public void testNullClause() { String headerStr = null; - try { - new FragmentHostHeader(headerStr); - fail("Null clause not allowed"); - } - catch (NullPointerException e) {} - catch (Exception e) { - fail("Null clause should result in NPE"); - } + assertThrows(NullPointerException.class, () -> new FragmentHostHeader(headerStr)); } @Test public void testEmptyClause() { String headerStr = ""; - try { - new FragmentHostHeader(headerStr); - fail("Empty clause not allowed"); - } - catch (IllegalArgumentException e) {} - catch (Exception e) { - fail("Empty clause should result in IAE"); - } + assertThrows(IllegalArgumentException.class, () -> new FragmentHostHeader(headerStr)); } @Test public void testMultipleClauses() { String headerStr = "foo;bundle-version=1.0,bar"; - try { - new FragmentHostHeader(headerStr); - fail("Multiple clauses not allowed"); - } - catch (IllegalArgumentException e) {} - catch (Exception e) { - fail("Multiple cluases should result in IAE"); - } + assertThrows(IllegalArgumentException.class, () -> new FragmentHostHeader(headerStr)); } @Test diff --git a/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/archive/GenericHeaderTest.java b/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/archive/GenericHeaderTest.java index cd47471a1..ad50c73c6 100644 --- a/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/archive/GenericHeaderTest.java +++ b/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/archive/GenericHeaderTest.java @@ -18,24 +18,19 @@ */ package org.apache.aries.subsystem.core.archive; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - import org.junit.Test; +import static org.junit.Assert.assertEquals; + public class GenericHeaderTest { - @Test - public void testEmptyHeader() { - try { - GenericHeader header = new GenericHeader("Foo-Bar", ""); - assertEquals( - "Empty headers are treated the same as those with an empty quoted string", - "\"\"", - header.getValue()); - assertEquals("Empty headers should have one clause", 1, header.getClauses().size()); - } - catch (Exception e) { - fail("Empty headers are allowed"); - } - } + @Test + public void testEmptyHeader() { + GenericHeader header = new GenericHeader("Foo-Bar", ""); + assertEquals( + "Empty headers are treated the same as those with an empty quoted string", + "\"\"", + header.getValue()); + assertEquals("Empty headers should have one clause", 1, header.getClauses().size()); + + } } diff --git a/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/internal/LocationTest.java b/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/internal/LocationTest.java index ff21e0795..d22884186 100644 --- a/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/internal/LocationTest.java +++ b/subsystem/subsystem-core/src/test/java/org/apache/aries/subsystem/core/internal/LocationTest.java @@ -15,39 +15,24 @@ package org.apache.aries.subsystem.core.internal; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; import java.net.MalformedURLException; +import java.net.URISyntaxException; import org.junit.Test; import org.osgi.framework.Version; public class LocationTest { @Test - public void testAnyLocationString() { + public void testAnyLocationString() throws MalformedURLException, URISyntaxException { String locationStr = "anyLocation"; - Location location = null; - try { - location = new Location(locationStr); - } - catch (Throwable t) { - t.printStackTrace(); - fail("Any location string must be supported"); - } + Location location = new Location(locationStr); assertNull("Wrong symbolic name", location.getSymbolicName()); assertEquals("Wrong value", locationStr, location.getValue()); assertNull("Wrong version", location.getVersion()); - try { - location.open(); - fail("Opening a location that does not represent a URL should fail"); - } - catch (MalformedURLException e) { - // Okay - } - catch (Throwable t) { - t.printStackTrace(); - fail("Wrong exception"); - } + assertThrows(MalformedURLException.class, () -> location.open()); } @Test @@ -73,17 +58,7 @@ public class LocationTest { Location location = new Location(locationString); assertEquals(locationString, location.getValue()); - try { - String sn = location.getSymbolicName(); - fail("Expecting an error: " + sn); - } catch (IllegalArgumentException e) { - // expected - } - try { - Version v = location.getVersion(); - fail("Expecting an error: " + v); - } catch (IllegalArgumentException e) { - // expected - } + assertThrows(IllegalArgumentException.class, () -> location.getSymbolicName()); + assertThrows(IllegalArgumentException.class, () -> location.getVersion()); } } diff --git a/subsystem/subsystem-modeller/src/test/java/org/apache/aries/subsystem/modelling/utils/DeployedBundlesTest.java b/subsystem/subsystem-modeller/src/test/java/org/apache/aries/subsystem/modelling/utils/DeployedBundlesTest.java index a4e2afc25..5e2359988 100644 --- a/subsystem/subsystem-modeller/src/test/java/org/apache/aries/subsystem/modelling/utils/DeployedBundlesTest.java +++ b/subsystem/subsystem-modeller/src/test/java/org/apache/aries/subsystem/modelling/utils/DeployedBundlesTest.java @@ -20,8 +20,8 @@ package org.apache.aries.subsystem.modelling.utils; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Arrays; @@ -139,7 +139,7 @@ public final class DeployedBundlesTest /** * Check the actual results match the expected values, regardless of order of the parts. - * @param entry the actual manifest entry. + * @param actual the actual manifest entry. * @param expected the expected manifest entry. * @return true if they match; false otherwise. */ @@ -220,19 +220,10 @@ public final class DeployedBundlesTest public void testGetImportPackage_Valid() throws Exception { // Check the import package entry is correct. - String importPackageEntry = null; - try - { DeployedBundles deployedBundles = validDeployedBundles(); packagesResolve(deployedBundles); - - importPackageEntry = deployedBundles.getImportPackage(); - } - catch (ResolverException e) - { - e.printStackTrace(); - fail(e.toString()); - } + + String importPackageEntry = deployedBundles.getImportPackage(); String expectedResult = "package.c;version=\"1.0.0\";bundle-symbolic-name=\"bundle.c\";bundle-version=\"[1.0.0,1.0.0]\"," + "package.d;version=\"1.0.0\";bundle-symbolic-name=\"bundle.d\";bundle-version=\"[1.0.0,1.0.0]\"," @@ -293,16 +284,7 @@ public final class DeployedBundlesTest // Check that package D is not duplicated in Import-Package, and that the version range // has been narrowed to the intersection of the original requirements. - String importPackageEntry = null; - try - { - importPackageEntry = deployedBundles.getImportPackage(); - } - catch (ResolverException e) - { - e.printStackTrace(); - fail(e.toString()); - } + String importPackageEntry = deployedBundles.getImportPackage(); String expectedResult = "package.d;version=\"[2.0.0,3.0.0)\""; assertTrue("ImportPackage=" + importPackageEntry, isEqual(importPackageEntry, expectedResult)); } @@ -321,16 +303,7 @@ public final class DeployedBundlesTest // Check that package C is not duplicated in Import-Package, and that the version range // has been narrowed to the intersection of the original requirements. - String importPackageEntry = null; - try - { - importPackageEntry = deployedBundles.getImportPackage(); - } - catch (ResolverException e) - { - e.printStackTrace(); - fail(e.toString()); - } + String importPackageEntry = deployedBundles.getImportPackage(); String expectedResult = "package.c;was_internal=\"true\";version=\"2.0.0\""; assertTrue("ImportPackage=" + importPackageEntry, isEqual(importPackageEntry, expectedResult)); } @@ -348,16 +321,7 @@ public final class DeployedBundlesTest new ArrayList<String>(), Arrays.asList("package.c;version=2.0.0;was_internal=true"))); // Check that the incompatible version requirements cannot be resolved. - String importPackageEntry = null; - try - { - importPackageEntry = deployedBundles.getImportPackage(); - fail("Expected exception. ImportPackage=" + importPackageEntry); - } - catch (ResolverException e) - { - // We expect to reach this point if the test passes. - } + assertThrows(ResolverException.class, () -> deployedBundles.getImportPackage()); } @Test @@ -373,16 +337,7 @@ public final class DeployedBundlesTest new ArrayList<String>(), Arrays.asList("package.c;version=2.0.0;was_internal=true"))); // Check that the incompatible package requirement attributes cause an exception. - String importPackageEntry = null; - try - { - importPackageEntry = deployedBundles.getImportPackage(); - fail("Expected exception. ImportPackage=" + importPackageEntry); - } - catch (ResolverException e) - { - // We expect to reach this point if the test passes. - } + assertThrows(ResolverException.class, () -> deployedBundles.getImportPackage()); } @@ -397,17 +352,8 @@ public final class DeployedBundlesTest new ArrayList<String>(), Arrays.asList("package.b;version=2.0.0"))); // Check that the bundle-symbolic-name attribute for a bundle within deployed-content is ok. - String importPackageEntry = null; - try - { - importPackageEntry = deployedBundles.getImportPackage(); - } - catch (ResolverException e) - { - e.printStackTrace(); - fail(e.toString()); - } - String expectedResult = ""; // All packages are satisfied internally + String importPackageEntry = deployedBundles.getImportPackage(); + String expectedResult = ""; // All packages are satisfied internally assertTrue("ImportPackage=" + importPackageEntry, isEqual(importPackageEntry, expectedResult)); } @@ -424,16 +370,7 @@ public final class DeployedBundlesTest // Check that the bundle-symbolic-name attribute for a bundle outside use-bundle causes an exception. - String importPackageEntry = null; - try - { - importPackageEntry = deployedBundles.getImportPackage(); - fail("Expected exception. ImportPackage=" + importPackageEntry); - } - catch (ResolverException e) - { - // We expect to reach this point if the test passes. - } + assertThrows(ResolverException.class, () -> deployedBundles.getImportPackage()); } @Test @@ -448,16 +385,7 @@ public final class DeployedBundlesTest // Check that the bundle-symbolic-name attribute for a bundle outside use-bundle causes an exception. - String importPackageEntry = null; - try - { - importPackageEntry = deployedBundles.getImportPackage(); - fail("Expected exception. ImportPackage=" + importPackageEntry); - } - catch (ResolverException e) - { - // We expect to reach this point if the test passes. - } + assertThrows(ResolverException.class, () -> deployedBundles.getImportPackage()); } @Test @@ -473,16 +401,7 @@ public final class DeployedBundlesTest new ArrayList<String>(), Arrays.asList("package.c;version=1.0.0"))); // Check that the resulting resolution directive is not optional. - String importPackageEntry = null; - try - { - importPackageEntry = deployedBundles.getImportPackage(); - } - catch (ResolverException e) - { - e.printStackTrace(); - fail(e.toString()); - } + String importPackageEntry = deployedBundles.getImportPackage(); String expectedResult = "package.c;version=1.0.0"; assertTrue("ImportPackage=" + importPackageEntry, isEqual(importPackageEntry, expectedResult)); } @@ -505,17 +424,8 @@ public final class DeployedBundlesTest // Check the redundant use-bundle entry is identified. // Bundle C is not required by app content, although it is specified in use-bundle. - Collection<ModelledResource> requiredUseBundle = null; - try - { - requiredUseBundle = deployedBundles.getRequiredUseBundle(); - } - catch (ResolverException e) - { - e.printStackTrace(); - fail(e.toString()); - } - assertTrue("RequiredUseBundle=" + requiredUseBundle, requiredUseBundle.size() == 1); + Collection<ModelledResource> requiredUseBundle = deployedBundles.getRequiredUseBundle(); + assertEquals("RequiredUseBundle=" + requiredUseBundle, 1, requiredUseBundle.size()); } @Test @@ -526,17 +436,8 @@ public final class DeployedBundlesTest packagesResolve(deployedBundles); // Check all the use-bundle entries are required. - Collection<ModelledResource> requiredUseBundle = null; - try - { - requiredUseBundle = deployedBundles.getRequiredUseBundle(); - } - catch (ResolverException e) - { - e.printStackTrace(); - fail(e.toString()); - } - assertTrue("RequiredUseBundle=" + requiredUseBundle, requiredUseBundle.size() == 2); + Collection<ModelledResource> requiredUseBundle = deployedBundles.getRequiredUseBundle(); + assertEquals("RequiredUseBundle=" + requiredUseBundle, 2, requiredUseBundle.size()); } //Inside cannot bundle-symbolic-name an outside bundle until the new RFC 138! @@ -551,17 +452,8 @@ public final class DeployedBundlesTest deployedBundles.addBundle(createModelledResource("bundle.b", "1.0.0", new ArrayList<String>(), Arrays.asList("package.b;version=1.0.0"))); - // Check that the bundle version requirement generates an error because it doesn't match the a bundle in use-bundle. - String importPackageEntry = null; - try - { - importPackageEntry = deployedBundles.getImportPackage(); - fail("Expected exception. ImportPackage=" + importPackageEntry); - } - catch (ResolverException e) - { - // We expect to reach this point if the test passes. - } + // Check that the bundle version requirement generates an error because it doesn't match the bundle in use-bundle. + assertThrows(ResolverException.class, () -> deployedBundles.getImportPackage()); } diff --git a/subsystem/subsystem-modeller/src/test/java/org/apache/aries/subsystem/modelling/utils/PackageRequirementMergerTest.java b/subsystem/subsystem-modeller/src/test/java/org/apache/aries/subsystem/modelling/utils/PackageRequirementMergerTest.java index a6c3b17ca..1cf75cd1d 100644 --- a/subsystem/subsystem-modeller/src/test/java/org/apache/aries/subsystem/modelling/utils/PackageRequirementMergerTest.java +++ b/subsystem/subsystem-modeller/src/test/java/org/apache/aries/subsystem/modelling/utils/PackageRequirementMergerTest.java @@ -37,8 +37,8 @@ import org.osgi.framework.Constants; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; public final class PackageRequirementMergerTest @@ -155,14 +155,9 @@ public final class PackageRequirementMergerTest PackageRequirementMerger merger = new PackageRequirementMerger(reqs); assertFalse(merger.isMergeSuccessful()); - - try - { - merger.getMergedRequirements(); - fail("getMergedRequirements should throw IllegalStateException."); - } - catch (IllegalStateException e) { } - + + assertThrows(IllegalStateException.class, () -> merger.getMergedRequirements()); + Set<String> result = merger.getInvalidRequirements(); Set<String> expected = new HashSet<String>(); expected.add("a"); @@ -234,14 +229,9 @@ public final class PackageRequirementMergerTest PackageRequirementMerger merger = new PackageRequirementMerger(reqs); assertFalse(merger.isMergeSuccessful()); - - try - { - merger.getMergedRequirements(); - fail("getMergedRequirements should throw IllegalStateException."); - } - catch (IllegalStateException e) { } - + + assertThrows(IllegalStateException.class, () -> merger.getMergedRequirements()); + Set<String> result = merger.getInvalidRequirements(); Set<String> expected = new HashSet<String>(); expected.add("a"); diff --git a/transaction/transaction-blueprint/pom.xml b/transaction/transaction-blueprint/pom.xml index e910cbf7b..969c66b92 100644 --- a/transaction/transaction-blueprint/pom.xml +++ b/transaction/transaction-blueprint/pom.xml @@ -24,7 +24,7 @@ <parent> <groupId>org.apache.aries</groupId> <artifactId>parent</artifactId> - <version>2.0.1</version> + <version>2.1.1</version> <relativePath>../../parent/pom.xml</relativePath> </parent> @@ -53,6 +53,7 @@ <easymock.version>5.5.0</easymock.version> <javax.transaction-api.version>1.2</javax.transaction-api.version> + <junit.version>4.13.2</junit.version> <maven-bundle-plugin.version>5.1.9</maven-bundle-plugin.version> <org.apache.aries.blueprint.core.version>1.0.0</org.apache.aries.blueprint.core.version> <osgi.cmpn.version>4.3.1</osgi.cmpn.version> @@ -98,6 +99,7 @@ <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> + <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> diff --git a/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction/TranStrategyTest.java b/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction/TranStrategyTest.java index 493d70eb2..723ca3a67 100644 --- a/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction/TranStrategyTest.java +++ b/transaction/transaction-blueprint/src/test/java/org/apache/aries/transaction/TranStrategyTest.java @@ -23,13 +23,18 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.fail; import java.util.HashSet; import java.util.Iterator; import java.util.Set; +import javax.transaction.HeuristicMixedException; +import javax.transaction.HeuristicRollbackException; +import javax.transaction.InvalidTransactionException; import javax.transaction.NotSupportedException; +import javax.transaction.RollbackException; import javax.transaction.Status; import javax.transaction.SystemException; import javax.transaction.Transaction; @@ -61,14 +66,10 @@ public class TranStrategyTest { // status is Status.STATUS_NO_TRANSACTION it should not return null. expect(tm.getStatus()).andReturn(Status.STATUS_NO_TRANSACTION); - try { + assertThrows(IllegalStateException.class, () -> { assertNotNull("TransactionStrategy.MANDATORY.begin(tm) returned null when manager " + "status is STATUS_NO_TRANSACTION", TransactionAttribute.MANDATORY.begin(tm).getActiveTransaction()); - } catch (IllegalStateException ise) { - // Expected to be in here - } catch (Exception e) { - fail("TransactionStrategy.MANDATORY.begin() threw an unexpected exception when tran manager status is STATUS_NO_TRANSACTION"); - } + }); // MANDATORY strategy should return null for all tran manager states other // than Status.STATUS_NO_TRANSACTION. @@ -81,25 +82,17 @@ public class TranStrategyTest { expect(tm.getStatus()).andReturn(invalids[i]); expect(tm.getTransaction()).andReturn(null); c.replay(); - try { Transaction tran = TransactionAttribute.MANDATORY.begin(tm).getActiveTransaction(); assertNull("TransactionStrategy.MANDATORY.begin() did not return null when manager status value is " + invalids[i], tran); - } catch (Exception ise) { - fail("TransactionStrategy.MANDATORY.begin() threw Exception when manager status value is " + invalids[i]); - } c.verify(); } } @Test - public void testMandatoryFinish() - { - try { + public void testMandatoryFinish() throws HeuristicRollbackException, SystemException, HeuristicMixedException, InvalidTransactionException, RollbackException { TransactionToken tranToken = new TransactionToken(t, null, TransactionAttribute.MANDATORY); TransactionAttribute.MANDATORY.finish(tm, tranToken); - } catch (Exception e) { - fail("TransactionStrategy.MANDATORY.finish() threw an unexpected exception"); - } + } @@ -110,13 +103,9 @@ public class TranStrategyTest { // status is Status.STATUS_ACTIVE it should not return null. expect(tm.getStatus()).andReturn(Status.STATUS_ACTIVE); - try { + assertThrows(IllegalStateException.class, () -> { assertNotNull("TransactionStrategy.NEVER.begin() returned null when manager status is STATUS_ACTIVE", TransactionAttribute.NEVER.begin(tm)); - } catch (IllegalStateException ise) { - // Expect to be in here - } catch (Exception e) { - fail("TransactionStrategy.NEVER.begin() threw an unexpected exception when tran manager status is STATUS_ACTIVE"); - } + }); // NEVER strategy should return null for all tran manager states other // than Status.STATUS_ACTIVE. @@ -129,25 +118,16 @@ public class TranStrategyTest { expect(tm.getStatus()).andReturn(invalids[i]); expect(tm.getTransaction()).andReturn(null).anyTimes(); c.replay(); - try { assertNull("TransactionStrategy.NEVER.begin() did not return null when manager status value is " + invalids[i], TransactionAttribute.NEVER.begin(tm).getActiveTransaction()); - } catch (Exception ise) { - fail("TransactionStrategy.NEVER.begin() threw unexpected exception when manager status value is " + invalids[i]); - } c.verify(); } } @Test - public void testNeverFinish() - { - try { + public void testNeverFinish() throws HeuristicRollbackException, SystemException, HeuristicMixedException, InvalidTransactionException, RollbackException { TransactionToken tranToken = new TransactionToken(null, null, TransactionAttribute.NEVER); TransactionAttribute.NEVER.finish(tm, tranToken); - } catch (Exception e) { - fail("TransactionStrategy.NEVER.finish() threw an unexpected exception"); - } } @Test @@ -172,22 +152,16 @@ public class TranStrategyTest { expect(tm.getStatus()).andReturn(invalids[i]); expect(tm.getTransaction()).andReturn(null).anyTimes(); c.replay(); - try { assertNull("TransactionStrategy.NOT_SUPPORTED.begin() did not return null when manager status value is " + invalids[i], TransactionAttribute.NOT_SUPPORTED.begin(tm).getActiveTransaction()); - } catch (Exception ise) { - fail("TransactionStrategy.NOT_SUPPORTED.begin() threw unexpected exception when manager status value is " + invalids[i]); - } c.verify(); } } @Test - public void testNotSupportedFinish() - { + public void testNotSupportedFinish() throws Exception { // If finish is called with a previously active transaction, then // we expect this transaction to be resumed for a NOT_SUPPORTED strategy - try { tm.resume(t); EasyMock.expectLastCall(); c.replay(); @@ -198,9 +172,6 @@ public class TranStrategyTest { c.reset(); tranToken = new TransactionToken(null, null, TransactionAttribute.NOT_SUPPORTED); TransactionAttribute.NOT_SUPPORTED.finish(tm, tranToken); - } catch (Exception e) { - fail("TransactionStrategy.NOT_SUPPORTED.finish() threw unexpected exception, " + e); - } } @Test @@ -227,11 +198,7 @@ public class TranStrategyTest { expect(tm.getStatus()).andReturn(invalids[i]); expect(tm.getTransaction()).andReturn(null); c.replay(); - try { assertNull("TransactionStrategy.REQUIRED.begin() did not return null when manager status value is " + invalids[i], TransactionAttribute.REQUIRED.begin(tm).getActiveTransaction()); - } catch (Exception ise) { - fail("TransactionStrategy.REQUIRED.begin() threw unexpected exception when manager status value is " + invalids[i]); - } c.verify(); } } @@ -311,11 +278,7 @@ public class TranStrategyTest { tm.begin(); expectLastCall(); c.replay(); - try { assertNull("TransactionStrategy.REQUIRES_NEW.begin() did not return null when manager status value is " + manStatus[i], TransactionAttribute.REQUIRES_NEW.begin(tm).getActiveTransaction()); - } catch (Exception ise) { - fail("TransactionStrategy.REQUIRES_NEW.begin() threw unexpected exception when manager status value is " + manStatus[i]); - } c.verify(); } @@ -368,8 +331,6 @@ public class TranStrategyTest { // or to be in here } catch (Exception thrownE) { fail("TransactionStrategy.REQUIRES_NEW.begin() threw unexpected exception when manager status is " + managerStatus); - } finally { - // If Status.STATUS_ACTIVE } c.verify(); c.reset(); @@ -391,25 +352,15 @@ public class TranStrategyTest { tm.resume(EasyMock.anyObject(Transaction.class)); expectLastCall(); c.replay(); - try { TransactionToken tranToken = new TransactionToken(t, t, TransactionAttribute.REQUIRES_NEW, true); TransactionAttribute.REQUIRES_NEW.finish(tm, tranToken); - } catch (Exception e) { - fail("TransactionStrategy.REQUIRES_NEW.finish() threw unexpected exception when manager status is " + allStates[i]); - } c.verify(); c.reset(); - try { expect(tm.getStatus()).andReturn(allStates[i]); requiresNew_assertion(tm, allStates[i]); c.replay(); - TransactionToken tranToken = new TransactionToken(t, null, TransactionAttribute.REQUIRES_NEW, true); - TransactionAttribute.REQUIRES_NEW.finish(tm, tranToken); - } catch (Throwable e) { - e.printStackTrace(); - fail("TransactionStrategy.REQUIRES_NEW.finish() threw unexpected exception when manager status is " + allStates[i]); - } finally { - } + TransactionToken tranToken2 = new TransactionToken(t, null, TransactionAttribute.REQUIRES_NEW, true); + TransactionAttribute.REQUIRES_NEW.finish(tm, tranToken2); c.verify(); } diff --git a/util/src/test/java/org/apache/aries/util/VersionRangeTest.java b/util/src/test/java/org/apache/aries/util/VersionRangeTest.java index f3298d421..ed7f11c61 100644 --- a/util/src/test/java/org/apache/aries/util/VersionRangeTest.java +++ b/util/src/test/java/org/apache/aries/util/VersionRangeTest.java @@ -23,8 +23,8 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import org.junit.Test; import org.osgi.framework.Version; @@ -148,30 +148,20 @@ public class VersionRangeTest @Test public void testExactVersion() throws Exception { - VersionRange vr; - try { - vr = new VersionRange("[1.0.0, 2.0.0]", true); - fail("from 1 to 2 not excludsive is not an exact range"); - } catch (IllegalArgumentException e) { - // expected - } - - vr = new VersionRange("[1.0.0, 1.0.0]", true); + assertThrows(IllegalArgumentException.class, () -> { + new VersionRange("[1.0.0, 2.0.0]", true); + }); + + VersionRange vr = new VersionRange("[1.0.0, 1.0.0]", true); assertTrue(vr.isExactVersion()); - - try { - vr = new VersionRange("(1.0.0, 1.0.0]", true); - fail("from 1 (not including 1) to 1, is not valid"); - } catch (IllegalArgumentException e) { - // expected - } - - try { - vr = new VersionRange("[1.0.0, 1.0.0)", true); - fail("sfrom 1 to 1 (not including 1), is not valid"); - } catch (IllegalArgumentException e) { - // expected - } + + assertThrows(IllegalArgumentException.class, () -> { + new VersionRange("(1.0.0, 1.0.0]", true); + }); + + assertThrows(IllegalArgumentException.class, () -> { + new VersionRange("[1.0.0, 1.0.0)", true); + }); vr = new VersionRange("1.0.0", true); assertTrue(vr.isExactVersion()); diff --git a/util/src/test/java/org/apache/aries/util/filesystem/FileSystemTest.java b/util/src/test/java/org/apache/aries/util/filesystem/FileSystemTest.java index f2af27c40..1b9c3ba59 100644 --- a/util/src/test/java/org/apache/aries/util/filesystem/FileSystemTest.java +++ b/util/src/test/java/org/apache/aries/util/filesystem/FileSystemTest.java @@ -23,8 +23,8 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import java.io.File; import java.io.FileInputStream; @@ -129,12 +129,9 @@ public class FileSystemTest { File baseDir = new File(getTestResourceDir(), "/app1"); File manifest = new File(baseDir, "META-INF/APPLICATION.MF"); - try { + assertThrows(IORuntimeException.class, () -> { FileSystem.getFSRoot(manifest); - fail("Should have thrown an IORuntimeException"); - } catch (IORuntimeException e) { - // good! - } + }); } /** diff --git a/util/src/test/java/org/apache/aries/util/filesystem/IOUtilsTest.java b/util/src/test/java/org/apache/aries/util/filesystem/IOUtilsTest.java index ca5cbc435..be87c3d75 100644 --- a/util/src/test/java/org/apache/aries/util/filesystem/IOUtilsTest.java +++ b/util/src/test/java/org/apache/aries/util/filesystem/IOUtilsTest.java @@ -177,18 +177,12 @@ public class IOUtilsTest @Override public void write(int b) throws IOException { - if(b!=data[idx++]){ - fail("Data written to outputstream was not as expected"); - } + assertEquals(b, data[idx++]); } }; IOUtils.copy(is,os); - if(is.available()!=123456789){ - fail("close was not invoked"); - } - - + assertEquals(is.available(),123456789); } @Test @@ -218,9 +212,7 @@ public class IOUtilsTest @Override public void write(int b) throws IOException { - if(b!=data[idx++]){ - fail("Data written to outputstream was not as expected"); - } + assertEquals(b, data[idx++]); } }; diff --git a/util/src/test/java/org/apache/aries/util/manifest/ManifestHeaderProcessorTest.java b/util/src/test/java/org/apache/aries/util/manifest/ManifestHeaderProcessorTest.java index a3c11faed..56d2dac43 100644 --- a/util/src/test/java/org/apache/aries/util/manifest/ManifestHeaderProcessorTest.java +++ b/util/src/test/java/org/apache/aries/util/manifest/ManifestHeaderProcessorTest.java @@ -23,8 +23,8 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Arrays; @@ -514,30 +514,20 @@ public class ManifestHeaderProcessorTest @Test public void testExactVersion() throws Exception { - VersionRange vr; - try { - vr = ManifestHeaderProcessor.parseVersionRange("[1.0.0, 2.0.0]", true); - fail("should not get here 1"); - } catch (IllegalArgumentException e) { - // expected - } + assertThrows(IllegalArgumentException.class, () -> { + ManifestHeaderProcessor.parseVersionRange("[1.0.0, 2.0.0]", true); + }); - vr = ManifestHeaderProcessor.parseVersionRange("[1.0.0, 1.0.0]", true); + VersionRange vr = ManifestHeaderProcessor.parseVersionRange("[1.0.0, 1.0.0]", true); assertTrue(vr.isExactVersion()); - try { - vr = ManifestHeaderProcessor.parseVersionRange("(1.0.0, 1.0.0]", true); - fail("should not get here 2"); - } catch (IllegalArgumentException e) { - // expected - } + assertThrows(IllegalArgumentException.class, () -> { + ManifestHeaderProcessor.parseVersionRange("(1.0.0, 1.0.0]", true); + }); - try { - vr = ManifestHeaderProcessor.parseVersionRange("[1.0.0, 1.0.0)", true); - fail("should not get here 3"); - } catch (IllegalArgumentException e) { - // expected - } + assertThrows(IllegalArgumentException.class, () -> { + ManifestHeaderProcessor.parseVersionRange("[1.0.0, 1.0.0)", true); + }); vr = ManifestHeaderProcessor.parseVersionRange("[1.0.0, 2.0.0]"); assertFalse(vr.isExactVersion()); diff --git a/versioning/versioning-checker/src/test/java/org/apache/aries/versioning/tests/FilterResultsTest.java b/versioning/versioning-checker/src/test/java/org/apache/aries/versioning/tests/FilterResultsTest.java index b782e44f6..566ded897 100644 --- a/versioning/versioning-checker/src/test/java/org/apache/aries/versioning/tests/FilterResultsTest.java +++ b/versioning/versioning-checker/src/test/java/org/apache/aries/versioning/tests/FilterResultsTest.java @@ -18,8 +18,9 @@ */ package org.apache.aries.versioning.tests; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; @@ -44,9 +45,8 @@ public class FilterResultsTest { * class, where the later versioned class has had a method removed. */ @Test - public void testApiMethodErrorExcluded() { + public void testApiMethodErrorExcluded() throws IOException { - try { File oldBundleFile = new File("../src/test/resources/api_1.0.0.jar"); BundleInfo oldBundle = new BundleInfo(BundleManifest.fromBundle(oldBundleFile), oldBundleFile); @@ -72,11 +72,7 @@ public class FilterResultsTest { String bundleElement = bundleCompatibility.getBundleElement(); String pkgElement = bundleCompatibility.getPkgElements().toString(); - assertTrue("Unexpected bundle versioning issue", bundleElement==null); - assertTrue("Unexpected package versioning issue", pkgElement.trim().length() == 0); - - } catch (IOException e) { - fail("Unexpected IOException " + e); - } + assertNull("Unexpected bundle versioning issue", bundleElement); + assertEquals("Unexpected package versioning issue", 0, pkgElement.trim().length()); } } diff --git a/web/web-urlhandler/src/test/java/org/apache/aries/web/converter/impl/WabConverterTest.java b/web/web-urlhandler/src/test/java/org/apache/aries/web/converter/impl/WabConverterTest.java index e435aed6d..22d0e5243 100644 --- a/web/web-urlhandler/src/test/java/org/apache/aries/web/converter/impl/WabConverterTest.java +++ b/web/web-urlhandler/src/test/java/org/apache/aries/web/converter/impl/WabConverterTest.java @@ -19,8 +19,8 @@ package org.apache.aries.web.converter.impl; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -224,15 +224,12 @@ public class WabConverterTest attrs.putValue(Constants.BUNDLE_VERSION, "1.0"); attrs.putValue(Constants.IMPORT_PACKAGE, "org.apache.util,org.apache.test;version=1.0"); attrs.putValue(Constants.BUNDLE_CLASSPATH, "jsp/classes"); - - try { - convertWithProperties(m, + + assertThrows(IOException.class, () -> { + convertWithProperties(m, WarToWabConverter.WEB_CONTEXT_PATH, "WebFiles", Constants.BUNDLE_SYMBOLICNAME, "foobar"); - fail("Conversion did not fail as expected"); - } catch (IOException e) { - // that's expected - } + }); } private Attributes convertWithProperties(Manifest m, String ... props) throws Exception {
