From 1e61ebdcad0aea45bb78627b231969f995a69f87 Mon Sep 17 00:00:00 2001 From: Gintas Grigelionis Date: Sun, 22 Apr 2018 09:24:03 +0200 Subject: [PATCH] More uses of expected exceptions, assumptions and/or matchers --- .../apache/tools/ant/AntClassLoaderTest.java | 53 +++-- .../org/apache/tools/ant/ProjectTest.java | 158 ++++++++------- .../apache/tools/ant/taskdefs/AntTest.java | 181 ++++++++---------- .../tools/ant/taskdefs/ParallelTest.java | 47 +++-- .../tools/ant/taskdefs/XmlPropertyTest.java | 27 ++- .../taskdefs/optional/RhinoScriptTest.java | 21 +- .../ant/taskdefs/optional/vss/MSVSSTest.java | 36 ++-- 7 files changed, 254 insertions(+), 269 deletions(-) diff --git a/src/tests/junit/org/apache/tools/ant/AntClassLoaderTest.java b/src/tests/junit/org/apache/tools/ant/AntClassLoaderTest.java index cf1c48c7d..bd9144ad9 100644 --- a/src/tests/junit/org/apache/tools/ant/AntClassLoaderTest.java +++ b/src/tests/junit/org/apache/tools/ant/AntClassLoaderTest.java @@ -23,7 +23,6 @@ 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 java.io.File; import java.io.IOException; @@ -38,6 +37,7 @@ import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; /** * Test case for ant class loader @@ -48,6 +48,9 @@ public class AntClassLoaderTest { @Rule public BuildFileRule buildRule = new BuildFileRule(); + @Rule + public ExpectedException thrown = ExpectedException.none(); + private AntClassLoader loader; @Before @@ -88,39 +91,33 @@ public class AntClassLoaderTest { assertEquals(mainjarstring + File.pathSeparator + extjarstring, path); } + /** + * The test should fail if NullPointException is thrown + * + * @throws ClassNotFoundException if a class is not found, ignored + */ @Test - public void testCleanup() throws BuildException { + public void testCleanup() throws ClassNotFoundException { + thrown.expect(ClassNotFoundException.class); Path path = new Path(buildRule.getProject(), "."); loader = buildRule.getProject().createClassLoader(path); try { // we don't expect to find this loader.findClass("fubar"); - fail("Did not expect to find fubar class"); - } catch (ClassNotFoundException e) { - // ignore expected - } - - loader.cleanup(); - try { - // we don't expect to find this - loader.findClass("fubar"); - fail("Did not expect to find fubar class"); - } catch (ClassNotFoundException e) { - // ignore expected - } catch (NullPointerException e) { - fail("loader should not fail even if cleaned up"); - } - - // tell the build it is finished - buildRule.getProject().fireBuildFinished(null); - try { - // we don't expect to find this - loader.findClass("fubar"); - fail("Did not expect to find fubar class"); - } catch (ClassNotFoundException e) { - // ignore expected - } catch (NullPointerException e) { - fail("loader should not fail even if project finished"); + } finally { + loader.cleanup(); + try { + // we don't expect to find this + loader.findClass("fubar"); + } finally { + // tell the build it is finished + buildRule.getProject().fireBuildFinished(null); + try { + // we don't expect to find this + loader.findClass("fubar"); + } finally { + } + } } } diff --git a/src/tests/junit/org/apache/tools/ant/ProjectTest.java b/src/tests/junit/org/apache/tools/ant/ProjectTest.java index c1b3f72d3..62d59ddf4 100644 --- a/src/tests/junit/org/apache/tools/ant/ProjectTest.java +++ b/src/tests/junit/org/apache/tools/ant/ProjectTest.java @@ -31,6 +31,7 @@ import org.apache.tools.ant.types.PatternSet; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.assertEquals; @@ -40,8 +41,8 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - +import static org.junit.Assume.assumeFalse; +import static org.junit.Assume.assumeTrue; /** * Very limited test class for Project. Waiting to be extended. @@ -52,6 +53,9 @@ public class ProjectTest { @Rule public BuildFileRule buildRule = new BuildFileRule(); + @Rule + public ExpectedException thrown = ExpectedException.none(); + private Project p; private String root; private MockBuildListener mbl; @@ -77,63 +81,75 @@ public class ProjectTest { } /** - * This test has been a starting point for moving the code to FileUtils. + * This test has been a starting point for moving the code to FileUtils; + * first, the DOS/Netware-specific part. + */ + @Test + public void testResolveFileWithDriveLetter() { + assumeTrue("Not DOS or Netware", Os.isFamily("netware") || Os.isFamily("dos")); + assertEqualsIgnoreDriveCase(localize(File.separator), + p.resolveFile("/", null).getPath()); + assertEqualsIgnoreDriveCase(localize(File.separator), + p.resolveFile("\\", null).getPath()); + /* + * throw in drive letters + */ + String driveSpec = "C:"; + String driveSpecLower = "c:"; + + assertEqualsIgnoreDriveCase(driveSpecLower + "\\", + p.resolveFile(driveSpec + "/", null).getPath()); + assertEqualsIgnoreDriveCase(driveSpecLower + "\\", + p.resolveFile(driveSpec + "\\", null).getPath()); + assertEqualsIgnoreDriveCase(driveSpecLower + "\\", + p.resolveFile(driveSpecLower + "/", null).getPath()); + assertEqualsIgnoreDriveCase(driveSpecLower + "\\", + p.resolveFile(driveSpecLower + "\\", null).getPath()); + /* + * promised to eliminate consecutive slashes after drive letter. + */ + assertEqualsIgnoreDriveCase(driveSpec + "\\", + p.resolveFile(driveSpec + "/////", null).getPath()); + assertEqualsIgnoreDriveCase(driveSpec + "\\", + p.resolveFile(driveSpec + "\\\\\\\\\\\\", null).getPath()); + } + + /** + * This test has been a starting point for moving the code to FileUtils; + * now, the POSIX-specific part. */ @Test public void testResolveFile() { - if (Os.isFamily("netware") || Os.isFamily("dos")) { - assertEqualsIgnoreDriveCase(localize(File.separator), + assumeFalse("DOS or Netware", Os.isFamily("netware") || Os.isFamily("dos")); + /* + * Start with simple absolute file names. + */ + assertEquals(File.separator, p.resolveFile("/", null).getPath()); - assertEqualsIgnoreDriveCase(localize(File.separator), + assertEquals(File.separator, p.resolveFile("\\", null).getPath()); - /* - * throw in drive letters - */ - String driveSpec = "C:"; - String driveSpecLower = "c:"; - - assertEqualsIgnoreDriveCase(driveSpecLower + "\\", - p.resolveFile(driveSpec + "/", null).getPath()); - assertEqualsIgnoreDriveCase(driveSpecLower + "\\", - p.resolveFile(driveSpec + "\\", null).getPath()); - assertEqualsIgnoreDriveCase(driveSpecLower + "\\", - p.resolveFile(driveSpecLower + "/", null).getPath()); - assertEqualsIgnoreDriveCase(driveSpecLower + "\\", - p.resolveFile(driveSpecLower + "\\", null).getPath()); - /* - * promised to eliminate consecutive slashes after drive letter. - */ - assertEqualsIgnoreDriveCase(driveSpec + "\\", - p.resolveFile(driveSpec + "/////", null).getPath()); - assertEqualsIgnoreDriveCase(driveSpec + "\\", - p.resolveFile(driveSpec + "\\\\\\\\\\\\", null).getPath()); - } else { - /* - * Start with simple absolute file names. - */ - assertEquals(File.separator, - p.resolveFile("/", null).getPath()); - assertEquals(File.separator, - p.resolveFile("\\", null).getPath()); - /* - * drive letters are not used, just to be considered as normal - * part of a name - */ - String driveSpec = "C:"; - String udir = System.getProperty("user.dir") + File.separatorChar; - assertEquals(udir + driveSpec, - p.resolveFile(driveSpec + "/", null).getPath()); - assertEquals(udir + driveSpec, - p.resolveFile(driveSpec + "\\", null).getPath()); - String driveSpecLower = "c:"; - assertEquals(udir + driveSpecLower, - p.resolveFile(driveSpecLower + "/", null).getPath()); - assertEquals(udir + driveSpecLower, - p.resolveFile(driveSpecLower + "\\", null).getPath()); - } /* - * Now test some relative file name magic. + * drive letters are not used, just to be considered as normal + * part of a name */ + String driveSpec = "C:"; + String udir = System.getProperty("user.dir") + File.separatorChar; + assertEquals(udir + driveSpec, + p.resolveFile(driveSpec + "/", null).getPath()); + assertEquals(udir + driveSpec, + p.resolveFile(driveSpec + "\\", null).getPath()); + String driveSpecLower = "c:"; + assertEquals(udir + driveSpecLower, + p.resolveFile(driveSpecLower + "/", null).getPath()); + assertEquals(udir + driveSpecLower, + p.resolveFile(driveSpecLower + "\\", null).getPath()); + } + + /** + * Test some relative file name magic: platform-neutral. + */ + @Test + public void testResolveRelativeFile() { assertEquals(localize("/1/2/3/4"), p.resolveFile("4", new File(localize("/1/2/3"))).getPath()); assertEquals(localize("/1/2/3/4"), @@ -168,8 +184,8 @@ public class ProjectTest { * is called via resolveFile to pass under cygwin */ private void assertEqualsIgnoreDriveCase(String s1, String s2) { - if ((Os.isFamily("dos") || Os.isFamily("netware")) - && s1.length() >= 1 && s2.length() >= 1) { + assumeTrue("Not DOS or Netware", Os.isFamily("netware") || Os.isFamily("dos")); + if (s1.length() >= 1 && s2.length() >= 1) { StringBuilder sb1 = new StringBuilder(s1); StringBuilder sb2 = new StringBuilder(s2); sb1.setCharAt(0, Character.toUpperCase(s1.charAt(0))); @@ -180,16 +196,14 @@ public class ProjectTest { } } - private void assertTaskDefFails(final Class taskClass, - final String message) { + private void assertTaskDefFails(final Class taskClass, final String message) { final String dummyName = "testTaskDefinitionDummy"; + thrown.expect(BuildException.class); + thrown.expectMessage(message); try { mbl.addBuildEvent(message, Project.MSG_ERR); p.addTaskDefinition(dummyName, taskClass); - fail(String.format("expected BuildException(\"%s\", Project.MSG_ERR) when adding task %s", - message, taskClass)); - } catch (BuildException e) { - assertEquals(message, e.getMessage()); + } finally { mbl.assertEmpty(); assertFalse(p.getTaskDefinitions().containsKey(dummyName)); } @@ -251,17 +265,14 @@ public class ProjectTest { assertTrue(p.getTaskDefinitions().contains(org.apache.tools.ant.taskdefs.Echo.class)); } + /** + * Fail because buildfile contains two targets with the same name + */ @Test public void testDuplicateTargets() { - // fail, because buildfile contains two targets with the same name - try { - buildRule.configureProject("src/etc/testcases/core/duplicate-target.xml"); - fail("Should throw BuildException about duplicate target"); - } catch (BuildException ex) { - assertEquals("specific message", - "Duplicate target 'twice'", - ex.getMessage()); - } + thrown.expect(BuildException.class); + thrown.expectMessage("Duplicate target 'twice'"); + buildRule.configureProject("src/etc/testcases/core/duplicate-target.xml"); } @Test @@ -279,16 +290,22 @@ public class ProjectTest { p.addBuildListener(new BuildListener() { public void buildStarted(BuildEvent event) { } + public void buildFinished(BuildEvent event) { } + public void targetStarted(BuildEvent event) { } + public void targetFinished(BuildEvent event) { } + public void taskStarted(BuildEvent event) { } + public void taskFinished(BuildEvent event) { } + public void messageLogged(final BuildEvent actual) { assertEquals(FOO, actual.getMessage()); // each of the following lines would cause an @@ -321,6 +338,7 @@ public class ProjectTest { @SuppressWarnings("unused") public DummyTaskPrivate() { } + public void execute() { } } @@ -328,6 +346,7 @@ public class ProjectTest { protected class DummyTaskProtected extends Task { public DummyTaskProtected() { } + public void execute() { } } @@ -335,6 +354,7 @@ public class ProjectTest { class DummyTaskPackage extends Task { public DummyTaskPackage() { } + public void execute() { } } diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/AntTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/AntTest.java index 0cb267487..3bd5b0cde 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/AntTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/AntTest.java @@ -19,8 +19,8 @@ package org.apache.tools.ant.taskdefs; import java.io.File; - -import junit.framework.AssertionFailedError; +import java.util.Arrays; +import java.util.List; import org.apache.tools.ant.BuildEvent; import org.apache.tools.ant.BuildException; @@ -42,7 +42,6 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** */ @@ -61,56 +60,49 @@ public class AntTest { buildRule.executeTarget("cleanup"); } - @Test + /** + * Fail due to recursive call + */ + @Test(expected = BuildException.class) public void test1() { - try { - buildRule.executeTarget("test1"); - fail("recursive call"); - } catch (BuildException ex) { - //TODO assert exception message - } + buildRule.executeTarget("test1"); + // TODO assert exception message } - // target must be specified - @Test + /** + * Fail due to unspecified target + */ + @Test(expected = BuildException.class) public void test2() { - try { - buildRule.executeTarget("test2"); - fail("required argument not specified"); - } catch (BuildException ex) { - //TODO assert exception message - } + buildRule.executeTarget("test2"); + // TODO assert exception message } - // Should fail since a recursion will occur... - @Test + /** + * Fail due to recursive call + */ + @Test(expected = BuildException.class) public void test3() { - try { - buildRule.executeTarget("test1"); - fail("recursive call"); - } catch (BuildException ex) { - //TODO assert exception message - } + buildRule.executeTarget("test3"); + // TODO assert exception message } - @Test + /** + * Fail due to empty target name + */ + @Test(expected = BuildException.class) public void test4() { - try { - buildRule.executeTarget("test4"); - fail("target attribute must not be empty"); - } catch (BuildException ex) { - //TODO assert exception message - } + buildRule.executeTarget("test4"); + // TODO assert exception message } - @Test + /** + * Fail due to nonexistent target + */ + @Test(expected = BuildException.class) public void test4b() { - try { - buildRule.executeTarget("test4b"); - fail("target doesn't exist"); - } catch (BuildException ex) { - //TODO assert exception message - } + buildRule.executeTarget("test4b"); + // TODO assert exception message } @Test @@ -165,7 +157,7 @@ public class AntTest { BasedirChecker bc = new BasedirChecker(dirs); buildRule.getProject().addBuildListener(bc); buildRule.executeTarget(target); - AssertionFailedError ae = bc.getError(); + AssertionError ae = bc.getError(); if (ae != null) { throw ae; } @@ -229,7 +221,7 @@ public class AntTest { ReferenceChecker rc = new ReferenceChecker(keys, expect, value); buildRule.getProject().addBuildListener(rc); buildRule.executeTarget(target); - AssertionFailedError ae = rc.getError(); + AssertionError ae = rc.getError(); if (ae != null) { throw ae; } @@ -238,21 +230,17 @@ public class AntTest { @Test public void testLogfilePlacement() { - File[] logFiles = new File[] { - buildRule.getProject().resolveFile("test1.log"), - buildRule.getProject().resolveFile("test2.log"), - buildRule.getProject().resolveFile("ant/test3.log"), - buildRule.getProject().resolveFile("ant/test4.log") - }; - for (File logFile : logFiles) { - assertFalse(logFile.getName() + " doesn\'t exist", logFile.exists()); - } + List logFiles = Arrays.asList(buildRule.getProject().resolveFile("test1.log"), + buildRule.getProject().resolveFile("test2.log"), + buildRule.getProject().resolveFile("ant/test3.log"), + buildRule.getProject().resolveFile("ant/test4.log")); + + logFiles.forEach(logFile -> assertFalse(logFile.getName() + " doesn\'t exist", + logFile.exists())); buildRule.executeTarget("testLogfilePlacement"); - for (File logFile : logFiles) { - assertTrue(logFile.getName() + " exists", logFile.exists()); - } + logFiles.forEach(logFile -> assertTrue(logFile.getName() + " exists", logFile.exists())); } @Test @@ -262,7 +250,7 @@ public class AntTest { InputHandlerChecker ic = new InputHandlerChecker(ih); buildRule.getProject().addBuildListener(ic); buildRule.executeTarget("tripleCall"); - AssertionFailedError ae = ic.getError(); + AssertionError ae = ic.getError(); if (ae != null) { throw ae; } @@ -273,13 +261,11 @@ public class AntTest { public void testRefId() { Path testPath = new Path(buildRule.getProject()); testPath.createPath().setPath(System.getProperty("java.class.path")); - PropertyChecker pc = - new PropertyChecker("testprop", - new String[] {null, - testPath.toString()}); + PropertyChecker pc = new PropertyChecker("testprop", + new String[] {null, testPath.toString()}); buildRule.getProject().addBuildListener(pc); buildRule.executeTarget("testRefid"); - AssertionFailedError ae = pc.getError(); + AssertionError ae = pc.getError(); if (ae != null) { throw ae; } @@ -290,7 +276,6 @@ public class AntTest { public void testUserPropertyWinsInheritAll() { buildRule.getProject().setUserProperty("test", "7"); buildRule.executeTarget("test-property-override-inheritall-start"); - assertThat(buildRule.getLog(), containsString("The value of test is 7")); } @@ -298,14 +283,12 @@ public class AntTest { public void testUserPropertyWinsNoInheritAll() { buildRule.getProject().setUserProperty("test", "7"); buildRule.executeTarget("test-property-override-no-inheritall-start"); - assertThat(buildRule.getLog(), containsString("The value of test is 7")); } @Test public void testOverrideWinsInheritAll() { buildRule.executeTarget("test-property-override-inheritall-start"); - assertThat(buildRule.getLog(), containsString("The value of test is 4")); } @@ -323,14 +306,13 @@ public class AntTest { assertThat(buildRule.getLog(), containsString("test1.x is 1")); } - @Test + /** + * Fail due to infinite recursion loop + */ + @Test(expected = BuildException.class) public void testInfiniteLoopViaDepends() { - try { - buildRule.executeTarget("infinite-loop-via-depends"); - fail("recursive call"); - } catch (BuildException ex) { - //TODO assert exception message - } + buildRule.executeTarget("infinite-loop-via-depends"); + // TODO assert exception message } @Test @@ -342,7 +324,6 @@ public class AntTest { @Test public void testTopLevelTarget() { buildRule.executeTarget("topleveltarget"); - assertEquals("Hello world", buildRule.getLog()); } @@ -355,11 +336,11 @@ public class AntTest { buildRule.getProject().addBuildListener(pcBar); buildRule.getProject().addBuildListener(pcFoo); buildRule.executeTarget("multiple-property-file-children"); - AssertionFailedError aeBar = pcBar.getError(); + AssertionError aeBar = pcBar.getError(); if (aeBar != null) { throw aeBar; } - AssertionFailedError aeFoo = pcFoo.getError(); + AssertionError aeFoo = pcFoo.getError(); if (aeFoo != null) { throw aeFoo; } @@ -367,14 +348,13 @@ public class AntTest { buildRule.getProject().removeBuildListener(pcFoo); } - @Test + /** + * Fail due to empty target name + */ + @Test(expected = BuildException.class) public void testBlankTarget() { - try { - buildRule.executeTarget("blank-target"); - fail("target name must not be empty"); - } catch (BuildException ex) { - //TODO assert exception message - } + buildRule.executeTarget("blank-target"); + // TODO assert exception message } @Test @@ -400,7 +380,7 @@ public class AntTest { private class BasedirChecker implements BuildListener { private String[] expectedBasedirs; private int calls = 0; - private AssertionFailedError error; + private AssertionError error; BasedirChecker(String[] dirs) { expectedBasedirs = dirs; @@ -432,16 +412,15 @@ public class AntTest { try { assertEquals(expectedBasedirs[calls++], event.getProject().getBaseDir().getAbsolutePath()); - } catch (AssertionFailedError e) { + } catch (AssertionError e) { error = e; } } } - AssertionFailedError getError() { + AssertionError getError() { return error; } - } private class ReferenceChecker implements BuildListener { @@ -449,7 +428,7 @@ public class AntTest { private boolean[] expectSame; private Object value; private int calls = 0; - private AssertionFailedError error; + private AssertionError error; ReferenceChecker(String[] keys, boolean[] expectSame, Object value) { this.keys = keys; @@ -481,8 +460,7 @@ public class AntTest { } if (error == null) { try { - String msg = - "Call " + calls + " refid=\'" + keys[calls] + "\'"; + String msg = "Call " + calls + " refid=\'" + keys[calls] + "\'"; if (value == null) { Object o = event.getProject().getReference(keys[calls]); if (expectSame[calls++]) { @@ -512,21 +490,20 @@ public class AntTest { } } } - } catch (AssertionFailedError e) { + } catch (AssertionError e) { error = e; } } } - AssertionFailedError getError() { + AssertionError getError() { return error; } - } private class InputHandlerChecker implements BuildListener { private InputHandler ih; - private AssertionFailedError error; + private AssertionError error; InputHandlerChecker(InputHandler value) { ih = value; @@ -535,18 +512,23 @@ public class AntTest { public void buildStarted(BuildEvent event) { check(event); } + public void buildFinished(BuildEvent event) { check(event); } + public void targetFinished(BuildEvent event) { check(event); } + public void taskStarted(BuildEvent event) { check(event); } + public void taskFinished(BuildEvent event) { check(event); } + public void messageLogged(BuildEvent event) { check(event); } @@ -560,23 +542,22 @@ public class AntTest { try { assertNotNull(event.getProject().getInputHandler()); assertSame(ih, event.getProject().getInputHandler()); - } catch (AssertionFailedError e) { + } catch (AssertionError e) { error = e; } } } - AssertionFailedError getError() { + AssertionError getError() { return error; } - } private class PropertyChecker implements BuildListener { private String[] expectedValues; private String key; private int calls = 0; - private AssertionFailedError error; + private AssertionError error; PropertyChecker(String key, String[] values) { this.key = key; @@ -606,25 +587,23 @@ public class AntTest { return; } if (calls >= expectedValues.length) { - error = new AssertionFailedError("Unexpected invocation of" - + " target " - + event.getTarget().getName()); + error = new AssertionError("Unexpected invocation of target " + + event.getTarget().getName()); } if (error == null) { try { assertEquals(expectedValues[calls++], event.getProject().getProperty(key)); - } catch (AssertionFailedError e) { + } catch (AssertionError e) { error = e; } } } - AssertionFailedError getError() { + AssertionError getError() { return error; } - } } diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/ParallelTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/ParallelTest.java index 603cf5789..dbf63255c 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/ParallelTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/ParallelTest.java @@ -27,9 +27,12 @@ import org.apache.tools.ant.Project; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasProperty; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertTrue; /** * Test of the parallel TaskContainer @@ -39,6 +42,9 @@ public class ParallelTest { @Rule public final BuildFileRule buildRule = new BuildFileRule(); + @Rule + public ExpectedException thrown = ExpectedException.none(); + /** Standard property value for the basic test */ public static final String DIRECT_MESSAGE = "direct"; /** Standard property value for the basic and fail test */ @@ -108,6 +114,9 @@ public class ParallelTest { int current = 0; int pos = beginSlash + 1; while (pos < lastPipe) { + assertTrue("Only expect '+-' in result count, found " + s.charAt(pos) + + " at position " + (pos + 1), + s.charAt(pos) == '+' || s.charAt(pos) == '-'); switch (s.charAt(pos++)) { case '+': current++; @@ -116,13 +125,10 @@ public class ParallelTest { current--; break; default: - fail("Only expect '+-' in result count, found " - + s.charAt(--pos) + " at position " + pos); - } - if (current > max) { - fail("Number of executing threads exceeded number allowed: " - + current + " > " + max); + break; } + assertTrue("Number of executing threads exceeded number allowed: " + + current + " > " + max, current <= max); } return lastPipe; } @@ -132,15 +138,12 @@ public class ParallelTest { @Test public void testFail() { // should get no output at all + thrown.expect(BuildException.class); + thrown.expectMessage(FAILURE_MESSAGE); Project p = buildRule.getProject(); p.setUserProperty("test.failure", FAILURE_MESSAGE); p.setUserProperty("test.delayed", DELAYED_MESSAGE); - try { - buildRule.executeTarget("testFail"); - fail("fail task in one parallel branch"); - } catch (BuildException ex) { - assertEquals(FAILURE_MESSAGE, ex.getMessage()); - } + buildRule.executeTarget("testFail"); } /** tests the demuxing of output streams in a multithreaded situation */ @@ -168,12 +171,9 @@ public class ParallelTest { */ @Test public void testSingleExit() { - try { - buildRule.executeTarget("testSingleExit"); - fail("ExitStatusException should have been thrown"); - } catch (ExitStatusException ex) { - assertEquals(42, ex.getStatus()); - } + thrown.expect(ExitStatusException.class); + thrown.expect(hasProperty("status", equalTo(42))); + buildRule.executeTarget("testSingleExit"); } /** @@ -181,12 +181,9 @@ public class ParallelTest { */ @Test public void testExitAndOtherException() { - try { - buildRule.executeTarget("testExitAndOtherException"); - fail("ExitStatusException should have been thrown"); - } catch (ExitStatusException ex) { - assertEquals(42, ex.getStatus()); - } + thrown.expect(ExitStatusException.class); + thrown.expect(hasProperty("status", equalTo(42))); + buildRule.executeTarget("testExitAndOtherException"); } } diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/XmlPropertyTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/XmlPropertyTest.java index 379f6be2d..0145757ea 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/XmlPropertyTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/XmlPropertyTest.java @@ -36,8 +36,11 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; /** */ @@ -228,18 +231,13 @@ public class XmlPropertyTest { // *value* of the Path object, though... Object obj = p.getReferences().get(currentKey); - if (obj == null) { - fail(assertMsg + " Object ID does not exist."); - } + assertNotEquals(assertMsg + " Object ID does not exist.", null, obj); // What is the property supposed to be? - propertyValue = - propertyValue.substring(3, propertyValue.length()); + propertyValue = propertyValue.substring(3, propertyValue.length()); if (propertyValue.equals("path")) { - if (!(obj instanceof Path)) { - fail(assertMsg + " Path ID is a " - + obj.getClass().getName()); - } + assertThat(assertMsg + " Path ID is a " + obj.getClass().getName(), + obj, instanceOf(Path.class)); } else { assertEquals(assertMsg, propertyValue, obj.toString()); } @@ -279,12 +277,9 @@ public class XmlPropertyTest { for (Map.Entry entry : references.entrySet()) { String currentKey = entry.getKey(); Object currentValue = entry.getValue(); - - if (!(currentValue instanceof Path) && !(currentValue instanceof String) - && !currentKey.startsWith("ant.")) { - fail(msg + "-" + inputFile.getName() + " Key=" - + currentKey + " is not a recognized type."); - } + assertTrue(msg + "-" + inputFile.getName() + " Key=" + currentKey + + " is not a recognized type.", currentValue instanceof Path + || currentValue instanceof String || currentKey.startsWith("ant.")); } } diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RhinoScriptTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RhinoScriptTest.java index 4a2aedae7..c8c33d624 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RhinoScriptTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RhinoScriptTest.java @@ -22,6 +22,7 @@ import org.apache.tools.ant.BuildFileRule; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -36,6 +37,9 @@ public class RhinoScriptTest { @Rule public BuildFileRule buildRule = new BuildFileRule(); + @Rule + public ExpectedException thrown = ExpectedException.none(); + @Before public void setUp() { buildRule.configureProject("src/etc/testcases/taskdefs/optional/script.xml"); @@ -68,22 +72,15 @@ public class RhinoScriptTest { @Test public void testUseSrcAndEncoding() { - final String readerEncoding = "UTF-8"; - buildRule.getProject().setProperty("useSrcAndEncoding.reader.encoding", readerEncoding); + buildRule.getProject().setProperty("useSrcAndEncoding.reader.encoding", "UTF-8"); buildRule.executeTarget("useSrcAndEncoding"); } @Test public void testUseSrcAndEncodingFailure() { - final String readerEncoding = "ISO-8859-1"; - buildRule.getProject().setProperty("useSrcAndEncoding.reader.encoding", readerEncoding); - try { - buildRule.executeTarget("useSrcAndEncoding"); - fail("should have failed with reader's encoding [" + readerEncoding - + "] different from the writer's encoding [" - + buildRule.getProject().getProperty("useSrcAndEncoding.encoding") + "]"); - } catch (BuildException e) { - assertTrue(e.getMessage().matches("expected but was ")); - } + thrown.expect(BuildException.class); + thrown.expectMessage("expected but was "); + buildRule.getProject().setProperty("useSrcAndEncoding.reader.encoding", "ISO-8859-1"); + buildRule.executeTarget("useSrcAndEncoding"); } } diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/vss/MSVSSTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/vss/MSVSSTest.java index 62fbea14b..77d32ab83 100644 --- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/vss/MSVSSTest.java +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/vss/MSVSSTest.java @@ -34,6 +34,7 @@ import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -65,6 +66,9 @@ public class MSVSSTest implements MSVSSConstants { public BuildFileRule buildRule = new BuildFileRule(); private Project project; + @Rule + public ExpectedException thrown = ExpectedException.none(); + @Before public void setUp() { project = new Project(); @@ -115,7 +119,7 @@ public class MSVSSTest implements MSVSSConstants { @Test public void testGetExceptions() { buildRule.configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml"); - expectSpecificBuildException("vssget.1", "some cause", "vsspath attribute must be set!"); + expectSpecificBuildException("vssget.1", "vsspath attribute must be set!"); } /** Tests Label commandline generation. */ @@ -168,8 +172,8 @@ public class MSVSSTest implements MSVSSConstants { @Test public void testLabelExceptions() { buildRule.configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml"); - expectSpecificBuildException("vsslabel.1", "some cause", "vsspath attribute must be set!"); - expectSpecificBuildException("vsslabel.2", "some cause", "label attribute must be set!"); + expectSpecificBuildException("vsslabel.1", "vsspath attribute must be set!"); + expectSpecificBuildException("vsslabel.2", "label attribute must be set!"); } /** Tests VSSHistory commandline generation with from label. */ @@ -262,17 +266,13 @@ public class MSVSSTest implements MSVSSConstants { @Test public void testHistoryExceptions() { buildRule.configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml"); - expectSpecificBuildException("vsshistory.1", "some cause", "vsspath attribute must be set!"); + expectSpecificBuildException("vsshistory.1", "vsspath attribute must be set!"); } - private void expectSpecificBuildException(String target, String failMessage, - String exceptionMessage) { - try { - buildRule.executeTarget(target); - fail(failMessage); - } catch (BuildException ex) { - assertEquals(exceptionMessage, ex.getMessage()); - } + private void expectSpecificBuildException(String target, String exceptionMessage) { + thrown.expect(BuildException.class); + thrown.expectMessage(exceptionMessage); + buildRule.executeTarget(target); } /** Tests CheckIn commandline generation. */ @@ -302,7 +302,7 @@ public class MSVSSTest implements MSVSSConstants { @Test public void testCheckinExceptions() { buildRule.configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml"); - expectSpecificBuildException("vsscheckin.1", "some cause", "vsspath attribute must be set!"); + expectSpecificBuildException("vsscheckin.1", "vsspath attribute must be set!"); } /** Tests CheckOut commandline generation. */ @@ -338,8 +338,8 @@ public class MSVSSTest implements MSVSSConstants { @Test public void testCheckoutExceptions() { buildRule.configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml"); - expectSpecificBuildException("vsscheckout.1", "some cause", "vsspath attribute must be set!"); - expectSpecificBuildException("vsscheckout.2", "some cause", "blah is not a legal value for this attribute"); + expectSpecificBuildException("vsscheckout.1", "vsspath attribute must be set!"); + expectSpecificBuildException("vsscheckout.2", "blah is not a legal value for this attribute"); } /** Tests Add commandline generation. */ @@ -371,7 +371,7 @@ public class MSVSSTest implements MSVSSConstants { @Test public void testAddExceptions() { buildRule.configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml"); - expectSpecificBuildException("vssadd.1", "some cause", "localPath attribute must be set!"); + expectSpecificBuildException("vssadd.1", "localPath attribute must be set!"); } /** Tests CP commandline generation. */ @@ -398,7 +398,7 @@ public class MSVSSTest implements MSVSSConstants { @Test public void testCpExceptions() { buildRule.configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml"); - expectSpecificBuildException("vsscp.1", "some cause", "vsspath attribute must be set!"); + expectSpecificBuildException("vsscp.1", "vsspath attribute must be set!"); } /** Tests Create commandline generation. */ @@ -429,7 +429,7 @@ public class MSVSSTest implements MSVSSConstants { @Test public void testCreateExceptions() { buildRule.configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml"); - expectSpecificBuildException("vsscreate.1", "some cause", "vsspath attribute must be set!"); + expectSpecificBuildException("vsscreate.1", "vsspath attribute must be set!"); } /**