junit4-4.11/0000755000175000017500000000000012131001325012170 5ustar ebourgebourgjunit4-4.11/build.xml0000644000175000017500000003117012050524441014024 0ustar ebourgebourg junit4-4.11/README0000644000175000017500000000002712050524441013060 0ustar ebourgebourgPlease read README.htmljunit4-4.11/acknowledgements.txt0000644000175000017500000001275012050524441016301 0ustar ebourgebourg2006 March 9 Matthias Schmidt: improved org.junit package javadoc 2006 August 3 giovanni: better test for TestCase without a name. Matthias Pfau: better error message when test case constructor fails 2006 November 21 dakcalouro: Found defect with comparing ints and longs (1555161) Ben Maurer: Found defect with timeouts taking twice as long as specified (1536198) 2007 February 08 Kazimierz Pogoda: Found defect with null array elements (1438163) 2007 July 09 wangqq: Found defect with @After not running after a timeout (1745048) 2007 July 18 Andrew Dick: Found defect with assertEquals comparing non-Integer Numbers (1715326) Michael Schechter: Found defect with Filters and suite() methods (1739095) 2008 February 5 Walter Gildersleeve: Found assertEquals(null, "null") defect (1857283) 2008 July 1 Johannes Link: Submitted test for running subclasses of Suite 2008 July 23 Daniel Brolund: Submitted patch for build.xml, fixing 1.5 compatibility (2021396) 2008 Aug 1 Nat Pryce: Found defect in treatment of validation errors from custom subclasses of the legacy JUnit4ClassRunner. 2008 Aug 18 Nir Soffer: Suggested adding to the cookbook information about running running JUnit from the command line. 2008 Aug 19 Jack Woehr: Discovered build.xml was missing from junit-4.x.zip 2009 Jan 5 Amanda Robinson: Fixed overly permissive @DataPoint processing. 2009 Feb 9 Mark Shapiro: Discovered bug in test counting after an ignored method (2106324) 2009 Apr 20 Chris Felaco: Discovered regression in handling suite() methods with JUnit 3 runner (1812200) Toby Byron: Suggested updating linking in javadoc (2090230) Raphael Parree: Improved docs on Parameterized (2186792) Robin de Silva Jayasinghe: Fixed Javadoc code sample for AfterClass (2126279) 2009 May 04 James Abbley: Submitted a patch that fixed the 2-second limit on Parallel execution. 2009 Nov 16 Kristian Rosenvold: Submitted a patch (github#16) that improves thread-safety of result counting 2010 Feb 08 Paul Holser: Submitted additional test for TestName rule. 2010 May 03 jonas22@github: Found bug (github#98) with assumptions and expected exceptions. 2011 Jan 03 jens.schauder@freenet.de: Found bug (github#74) with Categories and Parameterized. 2011 Jan 18 Markus Keller: Reported bug (github#163): Bad comparison failure message when using assertEquals(String, String) Kevin Cooney (kcooney@github): Patches for runLeaf, public multiple failure exception, assertion messages and null. 2011 Mar 04 Jerome Lacoste (lacostej@github) for initial patch for GH-191. 2011 Apr 15 reinholdfuereder@github For initial test for GH-39 2011 Apr 15 ububenheimer@github for bug report https://github.com/KentBeck/junit/issues/208 2011 Apr 29 reinholdfuereder@github: bug report, test, and fix for GH-38: ParentRunner filtering 2011 Apr 29 Markus Keller (mkeller@github): Report for GH-187: Unintentional dependency on Java 6 2011 May 31 Kevin Cooney (kcooney@github): Patches for filtering test suites: copy List returned by getChildren() before mutating it; optimize ParentRunner.filter for nested suites; optimize Filter.intersect for common cases 2011 Jun 06 Vampire@github: Report for GH-235: 4.7 release notes incorrect. 2011 Jun 24 Samuel Le Berrigaud (sleberrigaud@github): Report for GH-248: protected BlockJUnit4ClassRunner#rules method removed from 4.8.2 2011 Jun 24 Daniel Rothmaler (drothmaler@github): #299: random temp file/folder creation #300: ErrorCollector.checkThat overload 2011 Jun 25 Juan Cortez (jcortez@github): Fixed issue #219 where floats were being printed and represented as doubles in error messages. 2011 Jul 06 Stefan Birkner: Fixed wrong documentation of ClassRule (github#254). 2011 Jul 08 Paul Holser (pholser@alumni.rice.edu): Beginnings of fix for GH-64: Theories doesn't honor parameterized types 2011 Jul 09 Nigel Charman: Reported Rules bugs github#257 and gihub#258. 2011 Jul 09 Stefan Birkner: Fixed rules bugs (github#257, gihub#258, github#260). 2011 Jul 09 Stefan Birkner: Fixed rules bugs (github#257, gihub#258, github#260). 2011 Jul 16 Rob Dawson: Submitted a patch that makes Results serlializable. 2011 Jul 20 Asaf Ary, Stefan Birkner: Fixed FailOnTimeout class (github#265). 2011 Jul 22 Andreas Köhler, Stefan Birkner: Fixed wrong documentation of Parameterized (github#89). 2011 Jul 28 electrickery, Stefan Birkner: Fixed typo in JavaDoc (github#134). 2011 Aug 07 Esko Luontola: Fixed TemporaryFolder creating files in the current working directory (github#278). 2011 Aug 09 Stefan Birkner: Fixed JavaDoc links. 2011 Aug 10 rodolfoliviero@github and JoseRibeiro@github: feature to create recursive temporary folders. 2011 Aug 12 Esko Luontola: Fixed syntax error in Parameterized's usage example (github#285). 2011 Sep 09 Robert Munteanu, Stefan Birkner: TestWatcher and TestWatchman don't call failed when assumption is violated (github#296). digulla@github, Stefan Birkner: Removed useless code (github#289). == NOTE: as of September 2011, we have stopped recording contributions here. For a full list of everyone who has contributed great bug reports and code, please see http://github.com/KentBeck/junit junit4-4.11/.classpath0000644000175000017500000000074012050524441014165 0ustar ebourgebourg junit4-4.11/.gitignore0000644000175000017500000000014112050524441014165 0ustar ebourgebourgMaxCore.ser bin junit4.* target MaxCore.max # IntelliJ .idea *.ipr *.iml *.iws out java.hprof.txtjunit4-4.11/.cvsignore0000644000175000017500000000014312050524441014177 0ustar ebourgebourgbin junit4.1 junit*-SNAPSHOT-* target reports buildfile java.hprof.txt junit4.5-RC1 junit4.* *.ser junit4-4.11/stylesheet.css0000644000175000017500000000254412050524441015111 0ustar ebourgebourg/* Javadoc style sheet */ /* makes unvisted linkes red (red bad) */ A {color:red;} /* makes visted linkes the same green as the toolbar (green good) */ A:visited {color:#03A35D;} /* Define colors, fonts and other style attributes here to override the defaults */ /* Page background color */ body { background-color: #FFFFFF } /* Table colors */ .TableHeadingColor { background: #03A35D} /* Green */ .TableSubHeadingColor { background: #03A35D } /* Green */ .TableRowColor { background: #FFFFFF } /* White */ /* Font used in left-hand frame lists */ .FrameTitleFont { font-size: normal; font-family: normal } .FrameHeadingFont { font-size: normal; font-family: normal } .FrameItemFont { font-size: normal; font-family: normal } /* Example of smaller, sans-serif font in frames */ /* .FrameItemFont { font-size: 10pt; font-family: Helvetica, Arial, sans-serif } */ /* Navigation bar fonts and colors */ .NavBarCell1 { background-color:#03A35D;}/* Green */ .NavBarCell1Rev { background-color:#006400;}/* Dark green */ .NavBarFont1 { font-family: Arial, Helvetica, sans-serif; color:#000000;} .NavBarFont1Rev { font-family: Arial, Helvetica, sans-serif; color:#FFFFFF;} .NavBarCell2 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF;} .NavBarCell3 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF;} junit4-4.11/build_tests.sh0000755000175000017500000000345412050524441015067 0ustar ebourgebourgset -e set -o pipefail function TEST_BUILDING_in_zip { version=$(get_junit_version) ant zip unzip -l junit${version}/junit${version}.zip | grep BUILDING >/dev/null } function TEST_get_junit_version { version=$(get_junit_version) if [[ ! ($version == 4.*) ]]; then echo "Bad version: $version" return 1 fi } function TEST_ant_dist { version=$(get_junit_version) ant dist ls junit${version}/junit-${version}.jar } function TEST_ant_profile { rm -rf java.hprof.txt ant profile ls java.hprof.txt } function TEST_jars { version=$(get_junit_version) binjar=junit${version}/junit-${version}.jar srcjar=junit${version}/junit-${version}-src.jar depjar=junit${version}/junit-dep-${version}.jar ant clean ant jars jar tf $binjar | grep -q class \ && jar tf $srcjar | grep -q java \ && jar tf $depjar | grep -q class \ && jar tf $depjar | not grep hamcrest } function TEST_all_maven_jars { version=$(get_junit_version) binjar=junit${version}/junit-${version}.jar srcjar=junit${version}/junit-${version}-src.jar docjar=junit${version}/junit-${version}-javadoc.jar depbin=junit${version}/junit-dep-${version}.jar depsrc=junit${version}/junit-dep-${version}-src.jar depdoc=junit${version}/junit-dep-${version}-javadoc.jar ant clean ant all.maven.jars jar tf $binjar | grep -q class \ && jar tf $srcjar | grep -q java \ && jar tf $docjar | grep -q html \ && jar tf $depbin | grep -q class \ && jar tf $depsrc | grep -q java \ && jar tf $depdoc | grep -q html \ && jar tf $depbin | not grep hamcrest \ && jar tf $depsrc | not grep hamcrest \ && jar tf $depdoc | not grep hamcrest } function not { ! "$@" } function get_junit_version { ant print.version | grep echo | sed 's/.*echo..\([1-9].*\)/\1/' } source build/run_tests.shjunit4-4.11/CODING_STYLE0000644000175000017500000000523612050524441014055 0ustar ebourgebourg================================== Coding style ================================== ---------------------------------- Tabs and Indents ---------------------------------- * Tab size : 4 * Indent : 4 * Continuation indent : 8 * Label indent : 0 > Don't use tab characters. ---------------------------------- Spaces ---------------------------------- Before Parentheses * if parentheses * for parentheses * while parentheses * switch parentheses * try parentheses * catch parentheses * synchronized parentheses Around Operators * Assignment operators (=, +=, …) * Logical operators (&&, ||) * Equality operators (==, !=) * Relational operators (<, >, <=, >=) * Bitwise operators (&, |, ^) * Additive operators (+, -) * Multiplicative operators (*, /, %) * Shift operators (<<, >>, >>>) Before Left Brace * Class left brace * Method left brace * if left brace * else left brace * for left brace * while left brace * do left brace * switch left brace * try left brace * catch left brace * finally left brace * synchronized left brace Before Keywords * else keyword * while keyword * catch keyword * finally keyword In Ternary Operator (?:) * Before ? * After ? * Before : * After : Within Type Arguments * After comma Other * After comma * After semicolon * After type cast ---------------------------------- Wrapping and Braces ---------------------------------- Braces placement * In class declaration : End of line * In method declaration : End of line * Other : End of line Use Of Braces * if() statement : When multiline * for() statement : When multiline * while() statement : When multiline * do .. while() statement : When multiline Annotations * Class annotations : Wrap always * Method annotations : Wrap always * Field annotations : Wrap always * Paramater annotations : Do not wrap * Local variable annotations : Do not wrap ---------------------------------- Blank Lines ---------------------------------- Minimum Blank Lines * Before package statement : 0 * After package statement : 1 * Before imports : 1 * After imports : 1 * Around class : 1 * After class header : 0 * After anonymous class header : 0 * Around field in interface : 0 * Around field : 0 * Around method in interface : 1 * Around method : 1 * Before method body : 0 ---------------------------------- JavaDoc ---------------------------------- Alignment * Align thrown exception descriptions Blank Lines * After description Other * Enable leading asterisks * Use @throws rather than @exception * Keep empty lines ---------------------------------- Imports ---------------------------------- import static (all other imports) import java.* import javax.* import com.* import (all other imports)junit4-4.11/doc/0000755000175000017500000000000012050524441012746 5ustar ebourgebourgjunit4-4.11/doc/ReleaseNotes4.7.md0000644000175000017500000001243312050524441016115 0ustar ebourgebourg## Summary of Changes in version 4.7 ## ### Rules ### - Rules allow very flexible addition or redefinition of the behavior of each test method in a test class. Testers can reuse or extend one of the provided Rules below, or write their own. For more on this feature, see http://www.threeriversinstitute.org/blog/?p=155 - The TemporaryFolder Rule allows creation of files and folders that are guaranteed to be deleted when the test method finishes (whether it passes or fails): public static class HasTempFolder { @Rule public TemporaryFolder folder= new TemporaryFolder(); @Test public void testUsingTempFolder() throws IOException { File createdFile= folder.newFile("myfile.txt"); File createdFolder= folder.newFolder("subfolder"); // ... } } - ExternalResource is a base class for Rules (like TemporaryFolder) that set up an external resource before a test (a file, socket, server, database connection, etc.), and guarantee to tear it down afterward: public static class UsesExternalResource { Server myServer = new Server(); @Rule public ExternalResource resource = new ExternalResource() { @Override protected void before() throws Throwable { myServer.connect(); }; @Override protected void after() { myServer.disconnect(); }; }; @Test public void testFoo() { new Client().run(myServer); } } - The ErrorCollector Rule allows execution of a test to continue after the first problem is found (for example, to collect _all_ the incorrect rows in a table, and report them all at once): public static class UsesErrorCollectorTwice { @Rule public ErrorCollector collector= new ErrorCollector(); @Test public void example() { collector.addError(new Throwable("first thing went wrong")); collector.addError(new Throwable("second thing went wrong")); } } - Verifier is a base class for Rules like ErrorCollector, which can turn otherwise passing test methods into failing tests if a verification check is failed public static class ErrorLogVerifier() { private ErrorLog errorLog = new ErrorLog(); @Rule public MethodRule verifier = new Verifier() { @Override public void verify() { assertTrue(errorLog.isEmpty()); } } @Test public void testThatMightWriteErrorLog() { // ... } } - TestWatchman is a base class for Rules that take note of the testing action, without modifying it. For example, this class will keep a log of each passing and failing test: public static class WatchmanTest { private static String watchedLog; @Rule public MethodRule watchman= new TestWatchman() { @Override public void failed(Throwable e, FrameworkMethod method) { watchedLog+= method.getName() + " " + e.getClass().getSimpleName() + "\n"; } @Override public void succeeded(FrameworkMethod method) { watchedLog+= method.getName() + " " + "success!\n"; } }; @Test public void fails() { fail(); } @Test public void succeeds() { } } - The TestName Rule makes the current test name available inside test methods: public class NameRuleTest { @Rule public TestName name = new TestName(); @Test public void testA() { assertEquals("testA", name.getMethodName()); } @Test public void testB() { assertEquals("testB", name.getMethodName()); } } - The Timeout Rule applies the same timeout to all test methods in a class: public static class HasGlobalTimeout { public static String log; @Rule public MethodRule globalTimeout = new Timeout(20); @Test public void testInfiniteLoop1() { log+= "ran1"; for(;;) {} } @Test public void testInfiniteLoop2() { log+= "ran2"; for(;;) {} } } - The ExpectedException Rule allows in-test specification of expected exception types and messages: public static class HasExpectedException { @Rule public ExpectedException thrown= ExpectedException.none(); @Test public void throwsNothing() { } @Test public void throwsNullPointerException() { thrown.expect(NullPointerException.class); throw new NullPointerException(); } @Test public void throwsNullPointerExceptionWithMessage() { thrown.expect(NullPointerException.class); thrown.expectMessage("happened?"); thrown.expectMessage(startsWith("What")); throw new NullPointerException("What happened?"); } } ### Timeouts ### - Tests that time out now show the stack trace of the test thread. ### Matchers ### - Due to typing incompatibilities, JUnit is still including the 1.1 release of hamcrest. This is not a change from 4.6, but is a change from pre-beta releases of 4.7. Due to this incompatibility, tests using Hamcrest 1.2 must still use the MatcherAssert.assertThat method from Hamcrest, not Assert.assertThat from JUnit. ### Docs ### - Javadocs now link to online JDK javadocs (bug 2090230) - Parameterized runner javadocs improved (bug 2186792) - Fixed Javadoc code sample for AfterClass (2126279) - Fixed Javadoc for assertArraysEqual(float[], float[]) ### Bug fixes ### - Fixed: BaseTestRunner.getTest() requires class to extend TestCase (1812200) - Fixed: Suite does not allow for inheritance in annotations (2783118) - Fixed: ParallelComputer skipped tests that took longer than 2 seconds junit4-4.11/doc/ReleaseNotes4.8.2.html0000644000175000017500000000033312050524441016616 0ustar ebourgebourg

Summary of Changes in version 4.8.2

This was a quick bugfix release

Bug fixes

junit4-4.11/doc/markdown.sh0000644000175000017500000000007312050524441015124 0ustar ebourgebourg~/bin/Markdown.pl ReleaseNotes4.8.txt >ReleaseNotes4.8.htmljunit4-4.11/doc/ReleaseNotes4.9.1.md0000644000175000017500000000120312050524441016247 0ustar ebourgebourg## Summary of Changes in version 4.9.1 [unreleased!] ## ### Theories ### The `Theories` runner does not anticipate theory parameters that have generic types, as reported by github#64. Fixing this won't happen until `Theories` is moved to junit-contrib. In anticipation of this, 4.9.1 adds some of the necessary machinery to the runner classes, and deprecates a method that only the `Theories` runner uses, `FrameworkMethod`#producesType(). The Common Public License that JUnit is released under is now included in the source repository. Thanks to `@pholser` for identifying a potential resolution for github#64 and initiating work on it. junit4-4.11/doc/ReleaseNotes4.8.1.txt0000644000175000017500000000004012050524441016463 0ustar ebourgebourgPlease see ReleaseNotes4.8.1.md junit4-4.11/doc/ReleaseNotes4.9.1.txt0000644000175000017500000000004012050524441016464 0ustar ebourgebourgPlease see ReleaseNotes4.9.1.md junit4-4.11/doc/ReleaseNotes4.10.md0000644000175000017500000000635412050524441016174 0ustar ebourgebourg## Summary of Changes in version 4.10 ## Thanks to a full cast of contributors of bug fixes and new features. A full summary of commits between 4.9 and 4.10 is on [github](https://github.com/KentBeck/junit/compare/r4.9...4.10) ### junit-dep has correct contents ### junit-dep-4.9.jar incorrectly contained hamcrest classes, which could lead to version conflicts in projects that depend on hamcrest directly. This is fixed in 4.10 [@dsaff, closing gh-309] ### RuleChain ### The RuleChain rule allows ordering of TestRules: public static class UseRuleChain { @Rule public TestRule chain= RuleChain .outerRule(new LoggingRule("outer rule") .around(new LoggingRule("middle rule") .around(new LoggingRule("inner rule"); @Test public void example() { assertTrue(true); } } writes the log starting outer rule starting middle rule starting inner rule finished inner rule finished middle rule finished outer rule ### TemporaryFolder ### - `TemporaryFolder#newFolder(String... folderNames)` creates recursively deep temporary folders [@rodolfoliviero, closing gh-283] - `TemporaryFolder#newFile()` creates a randomly named new file, and `#newFolder()` creates a randomly named new folder [@Daniel Rothmaler, closing gh-299] ### Theories ### The `Theories` runner does not anticipate theory parameters that have generic types, as reported by github#64. Fixing this won't happen until `Theories` is moved to junit-contrib. In anticipation of this, 4.9.1 adds some of the necessary machinery to the runner classes, and deprecates a method that only the `Theories` runner uses, `FrameworkMethod`#producesType(). The Common Public License that JUnit is released under is now included in the source repository. Thanks to `@pholser` for identifying a potential resolution for github#64 and initiating work on it. ### Bug fixes ### - Built-in Rules implementations - TemporaryFolder should not create files in the current working directory if applying the rule fails [@orfjackal, fixing gh-278] - TestWatcher and TestWatchman should not call failed for AssumptionViolatedExceptions [@stefanbirkner, fixing gh-296] - Javadoc bugs - Assert documentation [@stefanbirkner, fixing gh-134] - ClassRule [@stefanbirkner, fixing gh-254] - Parameterized [@stefanbirkner, fixing gh-89] - Parameterized, again [@orfjackal, fixing gh-285] - Miscellaneous - Useless code in RunAfters [@stefanbirkner, fixing gh-289] - Parameterized test classes should be able to have `@Category` annotations [@dsaff, fixing gh-291] - Error count should be initialized in junit.tests.framework.TestListenerTest [@stefanbirkner, fixing gh-225] - AssertionFailedError constructor shouldn't call super with null message [@stefanbirkner, fixing gh-318] - Clearer error message for non-static inner test classes [@stefanbirkner, fixing gh-42] ### Minor changes ### - Description, Result and Failure are Serializable [@ephox-rob, closing gh-101] - FailOnTimeout is reusable, allowing for retrying Rules [@stefanbirkner, closing gh-265] - New `ErrorCollector.checkThat` overload, that allows you to specify a reason [@drothmaler, closing gh-300] junit4-4.11/doc/ReleaseNotes4.8.2.md0000644000175000017500000000030012050524441016244 0ustar ebourgebourg## Summary of Changes in version 4.8.2 ## This was a quick bugfix release ### Bug fixes ### - github#96: TestSuite(MyTestCase.class) should dynamically detect if MyTestCase is a TestCase junit4-4.11/doc/ReleaseNotes4.4.html0000644000175000017500000002756112050524441016466 0ustar ebourgebourg

Summary of Changes in version 4.5

Categories

Each test method and test class can be annotated as belonging to a category:

public static class SomeUITests {
    @Category(UserAvailable.class)
    @Test
    public void askUserToPressAKey() { }

    @Test
    public void simulatePressingKey() { }
}

@Category(InternetConnected.class)
public static class InternetTests {
    @Test
    public void pingServer() { }
}

To run all of the tests in a particular category, you must currently explicitly create a custom request:

new JUnitCore().run(Request.aClass(SomeUITests.class).inCategories(UserAvailable.class));

This feature will very likely be improved before the final release of JUnit 4.5

Miscellaneous

Summary of Changes in version 4.4

JUnit is designed to efficiently capture developers' intentions about their code, and quickly check their code matches those intentions. Over the last year, we've been talking about what things developers would like to say about their code that have been difficult in the past, and how we can make them easier.

Download

assertThat

Two years ago, Joe Walnes built a new assertion mechanism on top of what was then JMock 1. The method name was assertThat, and the syntax looked like this:

assertThat(x, is(3));
assertThat(x, is(not(4)));
assertThat(responseString, either(containsString("color")).or(containsString("colour")));
assertThat(myList, hasItem("3"));

More generally:

assertThat([value], [matcher statement]);

Advantages of this assertion syntax include:

We have decided to include this API directly in JUnit. It's an extensible and readable syntax, and it enables new features, like assumptions and theories.

Some notes:

Assumptions

Ideally, the developer writing a test has control of all of the forces that might cause a test to fail. If this isn't immediately possible, making dependencies explicit can often improve a design.
For example, if a test fails when run in a different locale than the developer intended, it can be fixed by explicitly passing a locale to the domain code.

However, sometimes this is not desirable or possible.
It's good to be able to run a test against the code as it is currently written, implicit assumptions and all, or to write a test that exposes a known bug. For these situations, JUnit now includes the ability to express "assumptions":

import static org.junit.Assume.*

@Test public void filenameIncludesUsername() {
   assumeThat(File.separatorChar, is('/'));
   assertThat(new User("optimus").configFileName(), is("configfiles/optimus.cfg"));
}

@Test public void correctBehaviorWhenFilenameIsNull() {
   assumeTrue(bugFixed("13356"));  // bugFixed is not included in JUnit
   assertThat(parse(null), is(new NullDocument()));
}

With this release, a failed assumption will lead to the test being marked as passing, regardless of what the code below the assumption may assert. In the future, this may change, and a failed assumption may lead to the test being ignored: however, third-party runners do not currently allow this option.

We have included assumeTrue for convenience, but thanks to the inclusion of Hamcrest, we do not need to create assumeEquals, assumeSame, and other analogues to the assert* methods. All of those functionalities are subsumed in assumeThat, with the appropriate matcher.

A failing assumption in a @Before or @BeforeClass method will have the same effect as a failing assumption in each @Test method of the class.

Theories

More flexible and expressive assertions, combined with the ability to state assumptions clearly, lead to a new kind of statement of intent, which we call a "Theory". A test captures the intended behavior in one particular scenario. A theory captures some aspect of the intended behavior in possibly infinite numbers of potential scenarios. For example:

@RunWith(Theories.class)
public class UserTest {
  @DataPoint public static String GOOD_USERNAME = "optimus";
  @DataPoint public static String USERNAME_WITH_SLASH = "optimus/prime";

  @Theory public void filenameIncludesUsername(String username) {
    assumeThat(username, not(containsString("/")));
    assertThat(new User(username).configFileName(), containsString(username));
  }
}

This makes it clear that the user's filename should be included in the config file name, only if it doesn't contain a slash. Another test or theory might define what happens when a username does contain a slash.

UserTest will attempt to run filenameIncludesUsername on every compatible DataPoint defined in the class. If any of the assumptions fail, the data point is silently ignored. If all of the assumptions pass, but an assertion fails, the test fails.

The support for Theories has been absorbed from the Popper project, and more complete documentation can be found there.

Defining general statements in this way can jog the developer's memory about other potential data points and tests, also allows automated tools to search for new, unexpected data points that expose bugs.

Other changes

This release contains other bug fixes and new features. Among them:

junit4-4.11/doc/ReleaseNotes4.8.html0000644000175000017500000000301112050524441016452 0ustar ebourgebourg

Summary of Changes in version 4.8

Categories

From a given set of test classes, the Categories runner runs only the classes and methods that are annotated with either the category given with the @IncludeCategory annotation, or a subtype of that category. Either classes or interfaces can be used as categories. Subtyping works, so if you say @IncludeCategory(SuperClass.class), a test marked @Category({SubClass.class}) will be run.

You can also exclude categories by using the @ExcludeCategory annotation

Example:

public interface FastTests { /* category marker */ }
public interface SlowTests { /* category marker */ }

public class A {
    @Test
    public void a() {
        fail();
    }

    @Category(SlowTests.class)
    @Test
    public void b() {
    }
}

@Category({SlowTests.class, FastTests.class})
public class B {
    @Test
    public void c() {

    }
}

@RunWith(Categories.class)
@IncludeCategory(SlowTests.class)
@SuiteClasses( { A.class, B.class }) // Note that Categories is a kind of Suite
public class SlowTestSuite {
  // Will run A.b and B.c, but not A.a
}

@RunWith(Categories.class)
@IncludeCategory(SlowTests.class)
@ExcludeCategory(FastTests.class)
@SuiteClasses( { A.class, B.class }) // Note that Categories is a kind of Suite
public class SlowTestSuite {
  // Will run A.b, but not A.a or B.c
}

Bug fixes

junit4-4.11/doc/faq/0000755000175000017500000000000012050524441013515 5ustar ebourgebourgjunit4-4.11/doc/faq/faq.htm0000644000175000017500000020535712050524441015012 0ustar ebourgebourg JUnit FAQ

JUnit FAQ


JUnit is a simple, open source framework to write and run repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks.


Edited by Mike Clark (http://clarkware.com)

Last modified on February 20, 2006


Table of Contents
  1. FAQ Info

    1. Who is responsible for this FAQ?
    2. How can I contribute to this FAQ?
    3. Where do I get the latest version of this FAQ?
  2. Overview

    1. What is JUnit?
    2. Where is the JUnit home page?
    3. Where are the JUnit mailing lists and forums?
    4. Where is the JUnit documentation?
    5. Where can I find articles on JUnit?
    6. What's the latest news on JUnit?
    7. How is JUnit licensed?
    8. What awards has JUnit won?
  3. Getting Started

    1. Where do I download JUnit?
    2. How do I install JUnit?
    3. How do I uninstall JUnit?
    4. How do I ask questions?
    5. How do I submit bugs, patches, or feature requests?
  4. Writing Tests

    1. How do I write and run a simple test?
    2. How do I use a test fixture?
    3. How do I test a method that doesn't return anything?
    4. Under what conditions should I test get() and set() methods?
    5. Under what conditions should I not test get() and set() methods?
    6. How do I write a test that passes when an expected exception is thrown?
    7. How do I write a test that fails when an unexpected exception is thrown?
    8. How do I test protected methods?
    9. How do I test private methods?
    10. Why does JUnit only report the first failure in a single test?
    11. In Java 1.4, 'assert' is a keyword. Won't this conflict with JUnit's assert() method?
    12. How do I test things that must be run in a J2EE container (e.g. servlets, EJBs)?
    13. Do I need to write a test class for every class I need to test?
    14. Is there a basic template I can use to create a test?
    15. How do I write a test for an abstract class?
    16. When are tests garbage collected?
  5. Organizing Tests

    1. Where should I put my test files?
    2. How can I run setUp() and tearDown() code once for all of my tests?
  6. Running Tests

    1. What CLASSPATH settings are needed to run JUnit?
    2. Why do I get a NoClassDefFoundError when trying to test JUnit or run the samples?
    3. How do I run JUnit from my command window?
    4. How do I run JUnit using Ant?
    5. How do I use Ant to create HTML test reports?
    6. How do I pass command-line arguments to a test execution?
    7. Why do I get a LinkageError when using XML interfaces in my test class?
    8. Why do I get the warning "AssertionFailedError: No tests found in XXX" when I run my test?
    9. Why do I see "Unknown Source" in the stack trace of a test failure, rather than the source file's line number?
    10. How do I organize all test classes in a TestSuite automatically and not use or manage a TestSuite explicitly?
  7. Best Practices

    1. When should tests be written?
    2. Do I have to write a test for everything?
    3. How simple is 'too simple to break'?
    4. How often should I run my tests?
    5. What do I do when a defect is reported?
    6. Why not just use System.out.println()?
    7. Why not just use a debugger?
  8. Miscellaneous

    1. How do I integrate JUnit with my IDE?
    2. How do I launch a debugger when a test fails?
    3. Where can I find unit testing frameworks similar to JUnit for other languages?
  1. Who is responsible for this FAQ?

    The current version of this FAQ is maintained by Mike Clark.

    Most of the wisdom contained in this FAQ comes from the collective insights and hard-won experiences of the many good folks who participate on the JUnit mailing list and the JUnit community at large.

    If you see your genius represented anywhere in this FAQ without due credit to you, please send me an email and I'll make things right.

  2. How can I contribute to this FAQ?

    Your contributions to this FAQ are greatly appreciated! The JUnit community thanks you in advance.

    To contribute to this FAQ, simply write a JUnit-related question and answer, then send the unformatted text to Mike Clark. Corrections to this FAQ are always appreciated, as well.

    No reasonable contribution will be denied. Your name will always appear along with any contribution you make.

  3. Where do I get the latest version of this FAQ?

    The master copy of this FAQ is available at http://junit.sourceforge.net/doc/faq/faq.htm.

    The JUnit distribution also includes this FAQ in the doc directory.

  1. What is JUnit?

    JUnit is a simple, open source framework to write and run repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks. JUnit features include:

    • Assertions for testing expected results
    • Test fixtures for sharing common test data
    • Test runners for running tests

    JUnit was originally written by Erich Gamma and Kent Beck.

  2. Where is the JUnit home page?

    The official JUnit home page is http://junit.org.

  3. Where are the JUnit mailing lists and forums?

    There are 3 mailing lists dedicated to everything JUnit:

  4. Where is the JUnit documentation?

    The following documents are included in the JUnit distribution in the doc directory:

  5. Where can I find articles on JUnit?

    The JUnit home page maintains a list of JUnit articles.

  6. What's the latest news on JUnit?

    The JUnit home page publishes the latest JUnit news.

  7. How is JUnit licensed?

    JUnit is Open Source Software, released under IBM's Common Public License Version 0.5 and hosted on SourceForge.

  8. What awards has JUnit won?

  1. Where do I download JUnit?

    The latest version of JUnit is available on SourceForge.

  2. How do I install JUnit?

    1. First, download the latest version of JUnit, referred to below as junit.zip.

    2. Then install JUnit on your platform of choice:

      Windows

      To install JUnit on Windows, follow these steps:

      1. Unzip the junit.zip distribution file to a directory referred to as %JUNIT_HOME%.

      2. Add JUnit to the classpath:

        set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%\junit.jar

      Unix (bash)

      To install JUnit on Unix, follow these steps:

      1. Unzip the junit.zip distribution file to a directory referred to as $JUNIT_HOME.

      2. Add JUnit to the classpath:

        export CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit.jar

    3. (Optional) Unzip the $JUNIT_HOME/src.jar file.

    4. Test the installation by running the sample tests distributed with JUnit. Note that the sample tests are located in the installation directory directly, not the junit.jar file. Therefore, make sure that the JUnit installation directory is on your CLASSPATH. Then simply type:

      java org.junit.runner.JUnitCore org.junit.tests.AllTests

      All the tests should pass with an "OK" message.

      If the tests don't pass, verify that junit.jar is in the CLASSPATH.

    5. Finally, read the documentation.

  3. How do I uninstall JUnit?

    1. Delete the directory structure where you unzipped the JUnit distribution.

    2. Remove junit.jar from the CLASSPATH.

    JUnit does not modify the registry so simply removing all the files will fully uninstall it.

  4. How do I ask questions?

    Questions that are not answered in the FAQ or in the documentation should be posted to the jGuru discussion forum or the JUnit user mailing list.

    Please stick to technical issues on the discussion forum and mailing lists. Keep in mind that these are public, so do not include any confidental information in your questions!

    You should also read "How to ask questions the smart way" by Eric Raymond before participating in the discussion forum and mailing lists.

    NOTE:
    Please do NOT submit bugs, patches, or feature requests to the discussion forum or mailing lists.
    Refer instead to "How do I submit bugs, patches, or feature requests?".

  5. How do I submit bugs, patches, or feature requests?

    JUnit celebrates programmers testing their own software. In this spirit, bugs, patches, and feature requests that include JUnit tests have a better chance of being addressed than those without.

    JUnit is hosted on SourceForge. Please use the tools provided by SourceForge for your submissions.

  1. How do I write and run a simple test?

    1. Create a class:

      
      	      
        package junitfaq;
      	      
        import org.junit.*;
        import static org.junit.Assert.*;
      
        import java.util.*;
        
        public class SimpleTest {
      	  
    2. Write a test method (annotated with @Test) that asserts expected results on the object under test:

      
      
          @Test
          public void testEmptyCollection() {
              Collection collection = new ArrayList();
              assertTrue(collection.isEmpty());
          }
      	  
    3. If you are running your JUnit 4 tests with a JUnit 3.x runner, write a suite() method that uses the JUnit4TestAdapter class to create a suite containing all of your test methods:

      
      
          public static junit.framework.Test suite() {
              return new junit.framework.JUnit4TestAdapter(SimpleTest.class);
          }
      	  
    4. Although writing a main() method to run the test is much less important with the advent of IDE runners, it's still possible:

      
      
          public static void main(String args[]) {
            org.junit.runner.JUnitCore.main("junitfaq.SimpleTest");
          }
        }
      	  
    5. Run the test:

      • To run the test from the console, type:

        java org.junit.runner.JUnitCore junitfaq.SimpleTest
      • To run the test with the test runner used in main(), type:

        java junitfaq.SimpleTest

      The passing test results in the following textual output:

      
      		.
      Time: 0
      
      OK (1 tests)
      	    
  2. How do I use a test fixture?

    (Submitted by: Jeff Nielsen)

    A test fixture is useful if you have two or more tests for a common set of objects. Using a test fixture avoids duplicating the code necessary to initialize (and cleanup) the common objects.

    Tests can use the objects (variables) in a test fixture, with each test invoking different methods on objects in the fixture and asserting different expected results. Each test runs in its own test fixture to isolate tests from the changes made by other tests. That is, tests don't share the state of objects in the test fixture. Because the tests are isolated, they can be run in any order.

    To create a test fixture, declare instance variables for the common objects. Initialize these objects in a public void method annotated with @Before. The JUnit framework automatically invokes any @Before methods before each test is run.

    The following example shows a test fixture with a common Collection object.

    
        package junitfaq;
    
        import org.junit.*;
        import static org.junit.Assert.*;
        import java.util.*;
    
        public class SimpleTest {
    
            private Collection<Object> collection;
    
            @Before
            public void setUp() {
                collection = new ArrayList<Object>();
            }
    
            @Test
            public void testEmptyCollection() {
                assertTrue(collection.isEmpty());
            }
    
    
            @Test
            public void testOneItemCollection() {
                collection.add("itemA");
                assertEquals(1, collection.size());
            }
        }
          

    Given this test, the methods might execute in the following order:

    setUp()
    testEmptyCollection()
    setUp()
    testOneItemCollection()

    The ordering of test-method invocations is not guaranteed, so testOneItemCollection() might be executed before testEmptyCollection(). But it doesn't matter, because each method gets its own instance of the collection.

    Although JUnit provides a new instance of the fixture objects for each test method, if you allocate any external resources in a @Before method, you should release them after the test runs by annotating a method with @After. The JUnit framework automatically invokes any @After methods after each test is run. For example:

    
        package junitfaq;
    
        import org.junit.*;
        import static org.junit.Assert.*;
        import java.io.*;
    
        public class OutputTest {
    
            private File output;
    
            @Before
            public void createOutputFile() {
                output = new File(...);
            }
    
            @After
            public void deleteOutputFile() {
                output.delete();
            }
    
            @Test
            public void testSomethingWithFile() {
                ...
            }
        }
          

    With this test, the methods will execute in the following order:

    
    createOutputFile()
    testSomethingWithFile()
    deleteOutputFile()
            
  3. How do I test a method that doesn't return anything?

    (Submitted by: Dave Astels)

    Often if a method doesn't return a value, it will have some side effect. Actually, if it doesn't return a value AND doesn't have a side effect, it isn't doing anything.

    There may be a way to verify that the side effect actually occurred as expected. For example, consider the add() method in the Collection classes. There are ways of verifying that the side effect happened (i.e. the object was added). You can check the size and assert that it is what is expected:

    
    
        @Test
        public void testCollectionAdd() {
            Collection collection = new ArrayList();
            assertEquals(0, collection.size());
            collection.add("itemA");
            assertEquals(1, collection.size());
            collection.add("itemB");
            assertEquals(2, collection.size());
        }
          

    Another approach is to make use of MockObjects.

    A related issue is to design for testing. For example, if you have a method that is meant to output to a file, don't pass in a filename, or even a FileWriter. Instead, pass in a Writer. That way you can pass in a StringWriter to capture the output for testing purposes. Then you can add a method (e.g. writeToFileNamed(String filename)) to encapsulate the FileWriter creation.

  4. Under what conditions should I test get() and set() methods?

    Unit tests are intended to alleviate fear that something might break. If you think a get() or set() method could reasonably break, or has in fact contributed to a defect, then by all means write a test.

    In short, test until you're confident. What you choose to test is subjective, based on your experiences and confidence level. Remember to be practical and maximize your testing investment.

    Refer also to "How simple is 'too simple to break'?".

  5. Under what conditions should I not test get() and set() methods?

    (Submitted by: J. B. Rainsberger)

    Most of the time, get/set methods just can't break, and if they can't break, then why test them? While it is usually better to test more, there is a definite curve of diminishing returns on test effort versus "code coverage". Remember the maxim: "Test until fear turns to boredom."

    Assume that the getX() method only does "return x;" and that the setX() method only does "this.x = x;". If you write this test:

    @Test
    public void testGetSetX() {
        setX(23);
        assertEquals(23, getX());
    }
          

    then you are testing the equivalent of the following:

    @Test
    public void testGetSetX() {
        x = 23;
        assertEquals(23, x);
    }
    

    or, if you prefer,

    @Test
    public void testGetSetX() {
        assertEquals(23, 23);
    }
    

    At this point, you are testing the Java compiler, or possibly the interpreter, and not your component or application. There is generally no need for you to do Java's testing for them.

    If you are concerned about whether a property has already been set at the point you wish to call getX(), then you want to test the constructor, and not the getX() method. This kind of test is especially useful if you have multiple constructors:

    @Test
    public void testCreate() {
        assertEquals(23, new MyClass(23).getX());
    }
          
  6. How do I write a test that passes when an expected exception is thrown?

    Add the optional expected attribute to the @Test annotation. The following is an example test that passes when the expected IndexOutOfBoundsException is raised:

    
    
        @Test(expected=IndexOutOfBoundsException.class)
        public void testIndexOutOfBoundsException() {
            ArrayList emptyList = new ArrayList();
    	Object o = emptyList.get(0);
        }
          
  7. How do I write a test that fails when an unexpected exception is thrown?

    Declare the exception in the throws clause of the test method and don't catch the exception within the test method. Uncaught exceptions will cause the test to fail with an error.

    The following is an example test that fails when the IndexOutOfBoundsException is raised:

    
    
        @Test
        public void testIndexOutOfBoundsExceptionNotRaised() 
            throws IndexOutOfBoundsException {
        
            ArrayList emptyList = new ArrayList();
            Object o = emptyList.get(0);
        }
          
  8. How do I test protected methods?

    Place your tests in the same package as the classes under test.

    Refer to "Where should I put my test files?" for examples of how to organize tests for protected method access.

  9. How do I test private methods?

    Testing private methods may be an indication that those methods should be moved into another class to promote reusability.

    But if you must...

    If you are using JDK 1.3 or higher, you can use reflection to subvert the access control mechanism with the aid of the PrivilegedAccessor. For details on how to use it, read this article.

  10. Why does JUnit only report the first failure in a single test?

    (Submitted by: J. B. Rainsberger)

    Reporting multiple failures in a single test is generally a sign that the test does too much, compared to what a unit test ought to do. Usually this means either that the test is really a functional/acceptance/customer test or, if it is a unit test, then it is too big a unit test.

    JUnit is designed to work best with a number of small tests. It executes each test within a separate instance of the test class. It reports failure on each test. Shared setup code is most natural when sharing between tests. This is a design decision that permeates JUnit, and when you decide to report multiple failures per test, you begin to fight against JUnit. This is not recommended.

    Long tests are a design smell and indicate the likelihood of a design problem. Kent Beck is fond of saying in this case that "there is an opportunity to learn something about your design." We would like to see a pattern language develop around these problems, but it has not yet been written down.

    Finally, note that a single test with multiple assertions is isomorphic to a test case with multiple tests:

    One test method, three assertions:

    
    public class MyTestCase {
        @Test
        public void testSomething() {
            // Set up for the test, manipulating local variables
            assertTrue(condition1);
            assertTrue(condition2);
            assertTrue(condition3);
        }
    }
          

    Three test methods, one assertion each:

    
    public class MyTestCase {
        // Local variables become instance variables
    
        @Before
        public void setUp() {
            // Set up for the test, manipulating instance variables
        }
        
        @Test
        public void testCondition1() {
            assertTrue(condition1);
        }
    
        @Test
        public void testCondition2() {
            assertTrue(condition2);
        }
    
        @Test
        public void testCondition3() {
            assertTrue(condition3);
        }
    }
          

    The resulting tests use JUnit's natural execution and reporting mechanism and, failure in one test does not affect the execution of the other tests. You generally want exactly one test to fail for any given bug, if you can manage it.

  11. In Java 1.4, assert is a keyword. Won't this conflict with JUnit's assert() method?

    JUnit 3.7 deprecated assert() and replaced it with assertTrue(), which works exactly the same way.

    JUnit 4 is compatible with the assert keyword. If you run with the -ea JVM switch, assertions that fail will be reported by JUnit.

  12. How do I test things that must be run in a J2EE container (e.g. servlets, EJBs)?

    Refactoring J2EE components to delegate functionality to other objects that don't have to be run in a J2EE container will improve the design and testability of the software.

    Cactus is an open source JUnit extension that can be used to test J2EE components in their natural environment.

  13. Do I need to write a test class for every class I need to test?

    (Submitted by: J. B. Rainsberger)

    No. It is a convention to start with one test class per class under test, but it is not necessary.

    Test classes only provide a way to organize tests, nothing more. Generally you will start with one test class per class under test, but then you may find that a small group of tests belong together with their own common test fixture.[1] In this case, you may move those tests to a new test class. This is a simple object-oriented refactoring: separating responsibilities of an object that does too much.

    Another point to consider is that the TestSuite is the smallest execution unit in JUnit: you cannot execute anything smaller than a TestSuite at one time without changing source code. In this case, you probably do not want to put tests in the same test class unless they somehow "belong together". If you have two groups of tests that you think you'd like to execute separately from one another, it is wise to place them in separate test classes.

    [1] A test fixture is a common set of test data and collaborating objects shared by many tests. Generally they are implemented as instance variables in the test class.

  14. Is there a basic template I can use to create a test?

    (Submitted by: Eric Armstrong)

    The following templates are a good starting point. Copy/paste and edit these templates to suit your coding style.

    SampleTest is a basic test template:

    
    import org.junit.*;
    import static org.junit.Assert.*;
    
    public class SampleTest {
    
        private java.util.List emptyList;
    
        /**
         * Sets up the test fixture. 
         * (Called before every test case method.)
         */
        @Before
        public void setUp() {
            emptyList = new java.util.ArrayList();
        }
    
        /**
         * Tears down the test fixture. 
         * (Called after every test case method.)
         */
        @After
        public void tearDown() {
            emptyList = null;
        }
        
        @Test
        public void testSomeBehavior() {
            assertEquals("Empty list should have 0 elements", 0, emptyList.size());
        }
    
        @Test(expected=IndexOutOfBoundsException.class)
        public void testForException() {
            Object o = emptyList.get(0);
        }
    }
          
  15. How do I write a test for an abstract class?

    Refer to http://c2.com/cgi/wiki?AbstractTestCases.

  16. When are tests garbage collected?

    (Submitted by: Timothy Wall and Kent Beck)

    By design, the tree of Test instances is built in one pass, then the tests are executed in a second pass. The test runner holds strong references to all Test instances for the duration of the test execution. This means that for a very long test run with many Test instances, none of the tests may be garbage collected until the end of the entire test run.

    Therefore, if you allocate external or limited resources in a test, you are responsible for freeing those resources. Explicitly setting an object to null in the tearDown() method, for example, allows it to be garbage collected before the end of the entire test run.

  1. Where should I put my test files?

    You can place your tests in the same package and directory as the classes under test.

    For example:

    src
       com
          xyz
             SomeClass.java
             SomeClassTest.java	 
          

    While adequate for small projects, many developers feel that this approach clutters the source directory, and makes it hard to package up client deliverables without also including unwanted test code, or writing unnecessarily complex packaging tasks.

    An arguably better way is to place the tests in a separate parallel directory structure with package alignment.

    For example:

    src
       com
          xyz
             SomeClass.java
    test
       com
          xyz
             SomeClassTest.java	 
          

    These approaches allow the tests to access to all the public and package visible methods of the classes under test.

    Some developers have argued in favor of putting the tests in a sub-package of the classes under test (e.g. com.xyz.test). The author of this FAQ sees no clear advantage to adopting this approach and believes that said developers also put their curly braces on the wrong line. :-)

  2. How can I run setUp() and tearDown() code once for all of my tests?

    The desire to do this is usually a symptom of excessive coupling in your design. If two or more tests must share the same test fixture state, then the tests may be trying to tell you that the classes under test have some undesirable dependencies.

    Refactoring the design to further decouple the classes under test and eliminate code duplication is usually a better investment than setting up a shared test fixture.

    But if you must...

    You can add a @BeforeClass annotation to a method to be run before all the tests in a class, and a @AfterClass annotation to a method to be run after all the tests in a class. Here's an example:

    
    
        package junitfaq;
    
        import org.junit.*;
        import static org.junit.Assert.*;
        import java.util.*;
        
        public class SimpleTest {
        
            private Collection collection;
    	
            @BeforeClass
            public static void oneTimeSetUp() {
                // one-time initialization code        
            }
    
            @AfterClass
            public static void oneTimeTearDown() {
                // one-time cleanup code
            }
    
            @Before
            public void setUp() {
                collection = new ArrayList();
            }
    	
            @After
            public void tearDown() {
                collection.clear();
            }
    
            @Test
            public void testEmptyCollection() {
                assertTrue(collection.isEmpty());
            }
    	
            @Test
            public void testOneItemCollection() {
                collection.add("itemA");
                assertEquals(1, collection.size());
            }
        }
          

    Given this test, the methods will execute in the following order:

    
    oneTimeSetUp()
    setUp()
    testEmptyCollection()
    tearDown()
    setUp()
    testOneItemCollection()
    tearDown()
    oneTimeTearDown()
    	
  1. What CLASSPATH settings are needed to run JUnit?

    (Submitted by: Eric Armstrong)

    To run your JUnit tests, you'll need the following elemements in your CLASSPATH:

    • JUnit class files
    • Your class files, including your JUnit test classes
    • Libraries your class files depend on

    If attempting to run your tests results in a NoClassDefFoundError, then something is missing from your CLASSPATH.

    Windows Example:

    set CLASSPATH=%JUNIT_HOME%\junit.jar;c:\myproject\classes;c:\myproject\lib\something.jar

    Unix (bash) Example:

    export CLASSPATH=$JUNIT_HOME/junit.jar:/myproject/classes:/myproject/lib/something.jar

  2. Why do I get a NoClassDefFoundError when trying to test JUnit or run the samples?

    (Submitted by: J.B. Rainsberger and Jason Rogers)

    Most likely your CLASSPATH doesn't include the JUnit installation directory.

    Refer to "What CLASSPATH settings are needed to run JUnit?" for more guidance.

    Also consider running WhichJunit to print the absolute location of the JUnit class files required to run and test JUnit and its samples.

    If the CLASSPATH seems mysterious, read this!

  3. How do I run JUnit from my command window?

    (Submitted by: Eric Armstrong)

    1. Set your CLASSPATH

    2. Invoke the runner:

      java org.junit.runner.JUnitCore <test class name>

  4. How do I run JUnit using Ant?

    (Submitted by: Eric Armstrong)

    1. Define any necessary Ant properties:

      
      <property name="src" value="./src" />
      <property name="lib" value="./lib" />
      <property name="classes" value="./classes" />
      <property name="test.class.name" value="com.xyz.MyTestSuite" />
      	  
    2. Set up the CLASSPATH to be used by JUnit:

      
      <path id="test.classpath">
        <pathelement location="${classes}" />
        <pathelement location="/path/to/junit.jar" />
        <fileset dir="${lib}">
          <include name="**/*.jar"/>
        </fileset>
      </path>
      	  
    3. Define the Ant task for running JUnit:

      
      <target name="test">
        <junit fork="yes" haltonfailure="yes">
          <test name="${test.class.name}" />
          <formatter type="plain" usefile="false" />
          <classpath refid="test.classpath" />
        </junit>
      </target>
      	  
    4. Run the test:

      ant test

    Refer to the JUnit Ant Task for more information.

  5. How do I use Ant to create HTML test reports?

    (Submitted by: Eric Armstrong and Steffen Gemkow)

    1. Ensure that Ant's optional.jar file is either in your CLASSPATH or exists in your $ANT_HOME/lib directory.

    2. Add an ANT property for the directory containing the HTML reports:

      <property name="test.reports" value="./reports" />
    3. Define the Ant task for running JUnit and generating reports:

      
      <target name="test-html">
        <junit fork="yes" printsummary="no" haltonfailure="no">
          <batchtest fork="yes" todir="${test.reports}" >
            <fileset dir="${classes}">
              <include name="**/*Test.class" />
            </fileset>
          </batchtest>
          <formatter type="xml" />
          <classpath refid="test.classpath" />
        </junit>
      
        <junitreport todir="${test.reports}">
          <fileset dir="${test.reports}">
            <include name="TEST-*.xml" />
          </fileset>
          <report todir="${test.reports}" />
        </junitreport>
      </target>
      	  
    4. Run the test:

      ant test-html

    Refer to the JUnit Ant Task for more information.

  6. How do I pass command-line arguments to a test execution?

    Use the -D JVM command-line options, as in:

    -DparameterName=parameterValue

    If the number of parameters on the command line gets unweildy, pass in the location of a property file that defines a set of parameters. Alternatively, the JUnit-addons package contains the XMLPropertyManager and PropertyManager classes that allow you to define a property file (or XML file) containing test parameters.

  7. Why do I get a LinkageError when using XML interfaces in my test?

    (Submitted by: Scott Stirling)

    The workaround as of JUnit 3.7 is to add org.w3c.dom.* and org.xml.sax.* to your excluded.properties.

    It's just a matter of time before this fix becomes incorporated into the released version of JUnit's excluded.properties, since JAXP is a standard part of JDK 1.4. It will be just like excluding org.omg.*. By the way, if you download the JUnit source from its Sourceforge CVS, you will find that these patterns have already been added to the default excluded.properties and so has a pattern for JINI. In fact, here is the current version in CVS, which demonstrates how to add exclusions to the list too:

    #
    # The list of excluded package paths for the TestCaseClassLoader
    #
    excluded.0=sun.*
    excluded.1=com.sun.*
    excluded.2=org.omg.*
    excluded.3=javax.*
    excluded.4=sunw.*
    excluded.5=java.*
    excluded.6=org.w3c.dom.*
    excluded.7=org.xml.sax.*
    excluded.8=net.jini.*
          

    This is the most common case where the default excluded.properties list needs modification. The cause of the LinkageError is related to using JAXP in your test cases. By JAXP I mean the whole set of javax.xml.* classes and the supporting org.w3c.dom.* and org.xml.sax.* classes.

    As stated above, the JUnit GUI TestRunners' classloader relies on the excluded.properties for classes it should delegate to the system classloader. JAXP is an unusual case because it is a standard Java extension library dependent on classes whose package names (org.w3c.dom.* and org.xml.sax.*) do not begin with a standard Java or Sun prefix. This is similar to the relationship between javax.rmi.* and the org.omg.* classes, which have been excluded by default in JUnit'ss excluded.properties for a while.

    What can happen, and frequently does when using the JUnit Swing or AWT UI with test cases that reference, use or depend on JAXP classes, such as Log4J, Apache SOAP, Axis, Cocoon, etc., is that the JUnit class loader (properly) delegates javax.xml.* classes it "sees" to the system loader. But then the system loader, in the process of initializing and loading that JAXP class, links and loads up a bunch of org.w3c.dom/org.xml.sax classes. When it does so, the JUnit custom classloader is not involved at all because the system classloader never delegates "down" or checks with custom classloaders to see if a class is already loaded. At any point after this, if the JUnit loader is asked to load an org.w3c.dom/org.xml.sax class that it's never seen before, it will try to load it because the class' name doesn't match any of the patterns in the default exclude list. That's when a LinkageError occurs. This is really a flaw in the JUnit classloader design, but there is the workaround given above.

    Java 2 JVMs keep classes (remember, classes and objects, though related, are different entities to the JVM - I'm talking about classes here, not object instances) in namespaces, identifying them by their fully qualified classname plus the instance of their defining (not initiating) loader. The JVM will attempt to assign all unloaded classes referenced by an already defined and loaded class to that class's defining loader. The JVM's classresolver routine (implemented as a C function in the JVM source code) keeps track of all these class loading events and "sees" if another classloader (such as the JUnit custom loader) attempts to define a class that has already been defined by the system loader. According to the rules of Java 2 loader constraints, in case a class has already been defined by the system loader, any attempts to load a class should first be delegated to the system loader. A "proper" way for JUnit to handle this feature would be to load classes from a repository other than the CLASSPATH that the system classloader knows nothing about. And then the JUnit custom classloader could follow the standard Java 2 delegation model, which is to always delegate class loading to the system loader, and only attempt to load if that fails. Since they both load from the CLASSPATH in the current model, if the JUnit loader delegated like it's supposed to, it would never get to load any classes since the system loader would always find them.

    You could try to hack around this in the JUnit source by catching the LinkageError in TestCaseClassLoader's loadClass() method and then making a recovery call to findSystemClass() -- thereby delegating to the system loader after the violation has been caught. But this hack only works some of the time, because now you can have the reverse problem where the JUnit loader will load a host of org.w3c.dom/org.xml.sax classes, and then the system loader violates the loader contraints at some point when it tries to do exactly what I described above with JAXP because it doesn't ever delegate to its logical child (the JUnit loader). Inevitably, if your test cases use many JAXP and related XML classes, one or the other classloader will end up violating the constraints whatever you do.

  8. Why do I get the warning "AssertionFailedError: No tests found in XXX" when I run my test?

    Make sure you have more or more method annotated with @Test.

    For example:

    @Test
    public void testSomething() {
    }
          
  9. Why do I see "Unknown Source" in the stack trace of a test failure, rather than the source file's line number?

    The debug option for the Java compiler must be enabled in order to see source file and line number information in a stack trace.

    When invoking the Java compiler from the command line, use the -g option to generate all debugging info.

    When invoking the Java compiler from an Ant task, use the debug="on" attribute. For example:

    <javac srcdir="${src}" destdir="${build}" debug="on" />

    When using older JVMs pre-Hotspot (JDK 1.1 and most/all 1.2), run JUnit with the -DJAVA_COMPILER=none JMV command line argument to prevent runtime JIT compilation from obscuring line number info.

    Compiling the test source with debug enabled will show the line where the assertion failed. Compiling the non-test source with debug enabled will show the line where an exception was raised in the class under test.

  10. How do I organize all test classes in a TestSuite automatically and not use or manage a TestSuite explicitly?

    (Submitted by: Bill de hora)

    There are a number of ways to do this:

    1. In Ant, use the junit task and the batchtest element:

      
      <junit printsummary="yes" haltonfailure="yes">
        ...
        <batchtest fork="yes">
          <fileset dir="${src.dir}">
             <include name="**/*Test.java" />
             <include name="**/Test*.java" />
          </fileset>
        </batchtest>
      </junit> 
      	  

      Idiomatic naming patterns for unit tests are Test*.java and *Test.java. Documentation and examples are at http://ant.apache.org/manual/OptionalTasks/junit.html.

    2. Use the DirectorySuiteBuilder and ArchiveSuiteBuilder (for jar/zip files) classes provided by JUnit-addons project:

      DirectorySuiteBuilder builder = new DirectorySuiteBuilder();
      builder.setSuffix("Test");
      Test suite = builer.suite("/home/project/myproject/tests"); 
      	  

      Documentation and examples are at http://junit-addons.sourceforge.net.

    3. Write your own custom suite builder.

      Have your test classes implement an interface and write a treewalker to load each class in a directory, inspect the class, and add any classes that implement the interface to a TestSuite.

      You might only want to do this if you are very uncomfortable with using a naming convention for test classes. Aside from being slow for larger suites, ultimately it's arguable whether it's more effort to follow a naming convention that have test classes implement an interface!

      An example of this approach is at http://www.javaworld.com/javaworld/jw-12-2000/jw-1221-junit_p.html.

  1. When should tests be written?

    Tests should be written before the code. Test-first programming is practiced by only writing new code when an automated test is failing.

    Good tests tell you how to best design the system for its intended use. They effectively communicate in an executable format how to use the software. They also prevent tendencies to over-build the system based on speculation. When all the tests pass, you know you're done!

    Whenever a customer test fails or a bug is reported, first write the necessary unit test(s) to expose the bug(s), then fix them. This makes it almost impossible for that particular bug to resurface later.

    Test-driven development is a lot more fun than writing tests after the code seems to be working. Give it a try!

  2. Do I have to write a test for everything?

    No, just test everything that could reasonably break.

    Be practical and maximize your testing investment. Remember that investments in testing are equal investments in design. If defects aren't being reported and your design responds well to change, then you're probably testing enough. If you're spending a lot of time fixing defects and your design is difficult to grow, you should write more tests.

    If something is difficult to test, it's usually an opportunity for a design improvement. Look to improve the design so that it's easier to test, and by doing so a better design will usually emerge.

  3. How simple is 'too simple to break'?

    (Submitted by: J. B. Rainsberger)

    The general philosophy is this: if it can't break on its own, it's too simple to break.

    First example is the getX() method. Suppose the getX() method only answers the value of an instance variable. In that case, getX() cannot break unless either the compiler or the interpreter is also broken. For that reason, don't test getX(); there is no benefit. The same is true of the setX() method, although if your setX() method does any parameter validation or has any side effects, you likely need to test it.

    Next example: suppose you have written a method that does nothing but forward parameters into a method called on another object. That method is too simple to break.

    public void myMethod(final int a, final String b) {
        myCollaborator.anotherMethod(a, b);
    }
          

    myMethod cannot possibly break because it does nothing: it forwards its input to another object and that's all.

    The only precondition for this method is "myCollaborator != null", but that is generally the responsibility of the constructor, and not of myMethod. If you are concerned, add a test to verify that myCollaborator is always set to something non-null by every constructor.

    The only way myMethod could break would be if myCollaborator.anotherMethod() were broken. In that case, test myCollaborator, and not the current class.

    It is true that adding tests for even these simple methods guards against the possibility that someone refactors and makes the methods "not-so-simple" anymore. In that case, though, the refactorer needs to be aware that the method is now complex enough to break, and should write tests for it -- and preferably before the refactoring.

    Another example: suppose you have a JSP and, like a good programmer, you have removed all business logic from it. All it does is provide a layout for a number of JavaBeans and never does anything that could change the value of any object. That JSP is too simple to break, and since JSPs are notoriously annoying to test, you should strive to make all your JSPs too simple to break.

    Here's the way testing goes:

    becomeTimidAndTestEverything
    while writingTheSameThingOverAndOverAgain
        becomeMoreAggressive
        writeFewerTests
        writeTestsForMoreInterestingCases
        if getBurnedByStupidDefect
            feelStupid
            becomeTimidAndTestEverything
        end
    end
          

    The loop, as you can see, never terminates.

  4. How often should I run my tests?

    Run all your unit tests as often as possible, ideally every time the code is changed. Make sure all your unit tests always run at 100%. Frequent testing gives you confidence that your changes didn't break anything and generally lowers the stress of programming in the dark.

    For larger systems, you may just run specific test suites that are relevant to the code you're working on.

    Run all your acceptance, integration, stress, and unit tests at least once per day (or night).

    If you're using Eclipse, be sure to check out David Saff's continuous testing plug-in.

  5. What do I do when a defect is reported?

    Test-driven development generally lowers the defect density of software. But we're all fallible, so sometimes a defect will slip through. When this happens, write a failing test that exposes the defect. When the test passes, you know the defect is fixed!

    Don't forget to use this as a learning opportunity. Perhaps the defect could have been prevented by being more aggressive about testing everything that could reasonably break.

  6. Why not just use System.out.println()?

    Inserting debug statements into code is a low-tech method for debugging it. It usually requires that output be scanned manually every time the program is run to ensure that the code is doing what's expected.

    It generally takes less time in the long run to codify expectations in the form of an automated JUnit test that retains its value over time. If it's difficult to write a test to assert expectations, the tests may be telling you that shorter and more cohesive methods would improve your design.

  7. Why not just use a debugger?

    Debuggers are commonly used to step through code and inspect that the variables along the way contain the expected values. But stepping through a program in a debugger is a manual process that requires tedious visual inspections. In essence, the debugging session is nothing more than a manual check of expected vs. actual results. Moreover, every time the program changes we must manually step back through the program in the debugger to ensure that nothing broke.

    It generally takes less time to codify expectations in the form of an automated JUnit test that retains its value over time. If it's difficult to write a test to assert expected values, the tests may be telling you that shorter and more cohesive methods would improve your design.

  1. How do I integrate JUnit with my IDE?

    The JUnit home page maintains a list of IDE integration instructions.

  2. How do I launch a debugger when a test fails?

    Start the TestRunner under the debugger and configure the debugger so that it catches the junit.framework.AssertionFailedError.

    How you configure this depends on the debugger you prefer to use. Most Java debuggers provide support to stop the program when a specific exception is raised.

    Notice that this will only launch the debugger when an expected failure occurs.

  3. Where can I find unit testing frameworks similar to JUnit for other languages?

    XProgramming.com maintains a complete list of available xUnit testing frameworks.


Valid XHTML 1.0!
junit4-4.11/doc/cookbook/0000755000175000017500000000000012050524441014554 5ustar ebourgebourgjunit4-4.11/doc/cookbook/cookbook.htm0000644000175000017500000001343512050524441017102 0ustar ebourgebourg JUnit Cookbook

JUnit Cookbook

Kent Beck, Erich Gamma



Here is a short cookbook showing you the steps you can follow in writing and organizing your own tests using JUnit.

Simple Test Case

How do you write testing code?

The simplest way is as an expression in a debugger. You can change debug expressions without recompiling, and you can wait to decide what to write until you have seen the running objects. You can also write test expressions as statements which print to the standard output stream. Both styles of tests are limited because they require human judgment to analyze their results. Also, they don't compose nicely- you can only execute one debug expression at a time and a program with too many print statements causes the dreaded "Scroll Blindness".

JUnit tests do not require human judgment to interpret, and it is easy to run many of them at the same time. When you need to test something, here is what you do:

  1. Annotate a method with @org.junit.Test
  2. When you want to check a value, import org.junit.Assert.* statically, call assertTrue() and pass a boolean that is true if the test succeeds
For example, to test that the sum of two Moneys with the same currency contains a value which is the sum of the values of the two Moneys, write:
@Test public void simpleAdd() {
    Money m12CHF= new Money(12, "CHF"); 
    Money m14CHF= new Money(14, "CHF"); 
    Money expected= new Money(26, "CHF"); 
    Money result= m12CHF.add(m14CHF); 
    assertTrue(expected.equals(result));
}
If you want to write a test similar to one you have already written, write a Fixture instead.

Fixture

What if you have two or more tests that operate on the same or similar sets of objects?

Tests need to run against the background of a known set of objects. This set of objects is called a test fixture. When you are writing tests you will often find that you spend more time writing the code to set up the fixture than you do in actually testing values.

To some extent, you can make writing the fixture code easier by paying careful attention to the constructors you write. However, a much bigger savings comes from sharing fixture code. Often, you will be able to use the same fixture for several different tests. Each case will send slightly different messages or parameters to the fixture and will check for different results.

When you have a common fixture, here is what you do:

  1. Add a field for each part of the fixture
  2. Annotate a method with @org.junit.Before and initialize the variables in that method
  3. Annotate a method with @org.junit.After to release any permanent resources you allocated in setUp
For example, to write several test cases that want to work with different combinations of 12 Swiss Francs, 14 Swiss Francs, and 28 US Dollars, first create a fixture:
public class MoneyTest { 
    private Money f12CHF; 
    private Money f14CHF; 
    private Money f28USD; 
    
    @Before public void setUp() { 
        f12CHF= new Money(12, "CHF"); 
        f14CHF= new Money(14, "CHF"); 
        f28USD= new Money(28, "USD"); 
    }
}
Once you have the Fixture in place, you can write as many Test Cases as you'd like. Add as many test methods (annotated with @Test) as you'd like.

Running Tests

How do you run your tests and collect their results?

Once you have tests, you'll want to run them. JUnit provides tools to define the suite to be run and to display its results. To run tests and see the results on the console, run this from a Java program:

org.junit.runner.JUnitCore.runClasses(TestClass1.class, ...);
or this from the command line, with both your test class and junit on the classpath:
java org.junit.runner.JUnitCore TestClass1.class [...other test classes...]
You make your JUnit 4 test classes accessible to a TestRunner designed to work with earlier versions of JUnit, declare a static method suite that returns a test.
public static junit.framework.Test suite() { 
    return new JUnit4TestAdapter(Example.class); 
}

Expected Exceptions

How do you verify that code throws exceptions as expected?

Verifying that code completes normally is only part of programming. Making sure the code behaves as expected in exceptional situations is part of the craft of programming too. For example:

new ArrayList<Object>().get(0); 
This code should throw an IndexOutOfBoundsException. The @Test annotation has an optional parameter "expected" that takes as values subclasses of Throwable. If we wanted to verify that ArrayList throws the correct exception, we would write:
@Test(expected= IndexOutOfBoundsException.class) public void empty() { 
    new ArrayList<Object>().get(0); 
}

junit4-4.11/doc/cookbook/logo.gif0000644000175000017500000000170412050524441016205 0ustar ebourgebourgGIF89a& ! ,&@HD#B(1 b(ѠE C,Ñ(KrHE/3tQI(mn̙Seŏ?<9TC'4h͖JD0hTX{N%!ή jҊ)wz'Χ3R-JnۥbE.W{;գU~D;q@;junit4-4.11/doc/ReleaseNotes4.6.html0000644000175000017500000000660712050524441016466 0ustar ebourgebourg

Summary of Changes in version 4.6

Max

JUnit now includes a new experimental Core, MaxCore. MaxCore remembers the results of previous test runs in order to run new tests out of order. MaxCore prefers new tests to old tests, fast tests to slow tests, and recently failing tests to tests that last failed long ago. There's currently not a standard UI for running MaxCore included in JUnit, but there is a UI included in the JUnit Max Eclipse plug-in at:

http://www.junitmax.com/junitmax/subscribe.html

Example:

public static class TwoUnEqualTests {
    @Test
    public void slow() throws InterruptedException {
        Thread.sleep(100);
        fail();
    }

    @Test
    public void fast() {
        fail();
    }
}

@Test
public void rememberOldRuns() {
    File maxFile = new File("history.max");
    MaxCore firstMax = MaxCore.storedLocally(maxFile);
    firstMax.run(TwoUnEqualTests.class);

    MaxCore useHistory= MaxCore.storedLocally(maxFile);
    List<Failure> failures= useHistory.run(TwoUnEqualTests.class)
            .getFailures();
    assertEquals("fast", failures.get(0).getDescription().getMethodName());
    assertEquals("slow", failures.get(1).getDescription().getMethodName());
}

Test scheduling strategies

JUnitCore now includes an experimental method that allows you to specify a model of the Computer that runs your tests. Currently, the only built-in Computers are the default, serial runner, and two runners provided in the ParallelRunner class: ParallelRunner.classes(), which runs classes in parallel, and ParallelRunner.methods(), which runs classes and methods in parallel.

This feature is currently less stable than MaxCore, and may be merged with MaxCore in some way in the future.

Example:

public static class Example {
    @Test public void one() throws InterruptedException {
        Thread.sleep(1000);
    }
    @Test public void two() throws InterruptedException {
        Thread.sleep(1000);
    }
}

@Test public void testsRunInParallel() {
    long start= System.currentTimeMillis();
    Result result= JUnitCore.runClasses(ParallelComputer.methods(),
            Example.class);
    assertTrue(result.wasSuccessful());
    long end= System.currentTimeMillis();
    assertThat(end - start, betweenInclusive(1000, 1500));
}

Comparing double arrays

Arrays of doubles can be compared, using a delta allowance for equality:

@Test
public void doubleArraysAreEqual() {
    assertArrayEquals(new double[] {1.0, 2.0}, new double[] {1.0, 2.0}, 0.01);
}

Filter.matchDescription API

Since 4.0, it has been possible to run a single method using the Request.method API. In 4.6, the filter that implements this is exposed as Filter.matchDescription.

Documentation

Bug fixes

junit4-4.11/doc/ReleaseNotes4.6.txt0000644000175000017500000000003612050524441016327 0ustar ebourgebourgPlease see ReleaseNotes4.6.md junit4-4.11/doc/ReleaseNotes4.10.html0000644000175000017500000000700612050524441016533 0ustar ebourgebourg

Summary of Changes in version 4.10 [unreleased!]

A full summary of commits between 4.9 and 4.10 is on github

junit-dep has correct contents

junit-dep-4.9.jar incorrectly contained hamcrest classes, which could lead to version conflicts in projects that depend on hamcrest directly. This is fixed in 4.10 [@dsaff, closing gh-309]

RuleChain

The RuleChain rule allows ordering of TestRules:

public static class UseRuleChain {
    @Rule
    public TestRule chain= RuleChain
                           .outerRule(new LoggingRule("outer rule")
                           .around(new LoggingRule("middle rule")
                           .around(new LoggingRule("inner rule");

    @Test
    public void example() {
        assertTrue(true);
    }
}

writes the log

starting outer rule
starting middle rule
starting inner rule
finished inner rule
finished middle rule
finished outer rule

TemporaryFolder

Theories

The Theories runner does not anticipate theory parameters that have generic types, as reported by github#64. Fixing this won't happen until Theories is moved to junit-contrib. In anticipation of this, 4.9.1 adds some of the necessary machinery to the runner classes, and deprecates a method that only the Theories runner uses, FrameworkMethod#producesType(). The Common Public License that JUnit is released under is now included in the source repository.

Thanks to @pholser for identifying a potential resolution for github#64 and initiating work on it.

Bug fixes

Minor changes

junit4-4.11/doc/ReleaseNotes4.5.md0000644000175000017500000000660112050524441016113 0ustar ebourgebourg## Summary of Changes in version 4.5 ## ### Installation ### - We are releasing `junit-4.5.jar`, which contains all the classes necessary to run JUnit, and `junit-dep-4.5.jar`, which leaves out hamcrest classes, for developers who already use hamcrest outside of JUnit. ### Basic JUnit operation ### - JUnitCore now more often exits with the correct exit code (0 for success, 1 for failure) - Badly formed test classes (exceptions in constructors, classes without tests, multiple constructors, Suite without @SuiteClasses) produce more helpful error messages - Test classes whose only test methods are inherited from superclasses now run. - Optimization to annotation processing can cut JUnit overhead by more than half on large test classes, especially when using Theories. [Bug 1796847] - A failing assumption in a constructor ignores the class - Correct results when comparing the string "null" with potentially null values. [Bug 1857283] - Annotating a class with `@RunWith(JUnit4.class)` will always invoke the default JUnit 4 runner in the current version of JUnit. This default changed from `JUnit4ClassRunner` in 4.4 to `BlockJUnit4ClassRunner` in 4.5 (see below), and may change again. ### Extension ### - `BlockJUnit4Runner` is a new implementation of the standard JUnit 4 test class functionality. In contrast to `JUnit4ClassRunner` (the old implementation): - `BlockJUnit4Runner` has a much simpler implementation based on Statements, allowing new operations to be inserted into the appropriate point in the execution flow. - `BlockJUnit4Runner` is published, and extension and reuse are encouraged, whereas `JUnit4ClassRunner` was in an internal package, and is now deprecated. - `ParentRunner` is a base class for runners that iterate over a list of "children", each an object representing a test or suite to run. `ParentRunner` provides filtering, sorting, `@BeforeClass`, `@AfterClass`, and method validation to subclasses. - `TestClass` wraps a class to be run, providing efficient, repeated access to all methods with a given annotation. - The new `RunnerBuilder` API allows extending the behavior of Suite-like custom runners. - `AssumptionViolatedException.toString()` is more informative ### Extra Runners ### - `Parameterized.eachOne()` has been removed - New runner `Enclosed` runs all static inner classes of an outer class. ### Theories ### - `@Before` and `@After` methods are run before and after each set of attempted parameters on a Theory, and each set of parameters is run on a new instance of the test class. - Exposed API's `ParameterSignature.getType()` and `ParameterSignature.getAnnotations()` - An array of data points can be introduced by a field or method marked with the new annotation `@DataPoints` - The Theories custom runner has been refactored to make it faster and easier to extend ### Development ### - Source has been split into directories `src/main/java` and `src/test/java`, making it easier to exclude tests from builds, and making JUnit more maven-friendly - Test classes in `org.junit.tests` have been organized into subpackages, hopefully making finding tests easier. - `ResultMatchers` has more informative descriptions. - `TestSystem` allows testing return codes and other system-level interactions. ### Incompatible changes ### - Removed Request.classes(String, Class...) factory method junit4-4.11/doc/homepage.html0000644000175000017500000001105312050524441015421 0ustar ebourgebourg JUnit

JUnit

JUnit is a simple framework to write repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks.

Getting Started

To get started with unit testing and JUnit read the article: JUnit Cookbook.
This article describes basic test writing using JUnit 4.

You find additional samples in the org.junit.samples package:

JUnit 4.x only comes with a textual TestRunner. For graphical feedback, most major IDE's support JUnit 4. If necessary, you can run JUnit 4 tests in a JUnit 3 environment by adding the following method to each test class:

public static Test suite() {
   return new JUnit4TestAdapter(ThisClass.class);
} 

Documentation

JUnit Cookbook
    A cookbook for implementing tests with JUnit.
Javadoc
    API documentation generated with javadoc.
Frequently asked questions
    Some frequently asked questions about using JUnit.
Release notes
    Latest JUnit release notes
License
    The terms of the common public license used for JUnit.
The following documents still describe JUnit 3.8.

The JUnit 3.8 version of this homepage
Test Infected - Programmers Love Writing Tests
    An article demonstrating the development process with JUnit.
JUnit - A cooks tour

JUnit Related Projects/Sites

Mailing Lists

There are three junit mailing lists:

Get Involved

JUnit celebrates programmers testing their own software. As a result bugs, patches, and feature requests which include JUnit TestCases have a better chance of being addressed than those without.
JUnit is forged on Sourceforge please use the tools provided for your submissions.
JUnit source code is now hosted on GitHub.
hosted by SourceForge Logo junit4-4.11/doc/testinfected/0000755000175000017500000000000012050524441015427 5ustar ebourgebourgjunit4-4.11/doc/testinfected/IMG00003.GIF0000644000175000017500000001355012050524441016761 0ustar ebourgebourgGIF89a @ @ @@@@@``@``@@@@ @ @ @ @@ @ @ ` `@ ` ` @ @ @ @ @@@@@@ @ @@ @ @@@@@@@@@@`@`@@`@`@@@@@@@@@@@@@@@@@@@@``@``` ` @` ` `@`@@`@`@````@``````@````@````@````@``@ @ @@@@@``@``@@@@@ @ @@@@@``@``@@@@@ @ @@@@@``@``@@@@@ @ @@@@@``@``@@@@!,  H*\ȰÇ#JHŋ3jȱǏɓ(S\ɲ˗0cʜI͛8sɳϟ@ F$I[H*]ʴӧPJJիXjʵׯ`ÊK֢#]˶۷pʝKݮh ߿ LÈ+^̸ǐ#KL˘3/FW)'zIͨS^ͺװc˞Q|Q6 N1E&G_i27mZtسkν wa:K}:~;.98߯xԼ ږ6^ӕ^o!'!{EXe_T(!%R'}vZ`ƈᄈG$SC"YbR*u^m,2HaQ%tby%_&e|Jcj衫ԙKG nv4'{N _}qjd6(D"fI9zYN8 ka2*jbjκ}kkbdž+nm l(knjV;jz:Hc#j:J^Kb)W n ®sD$lc,,R0p1|xV<3_ -t@-b7O?7ӲI TW we\w`bmhZp-tvx|߀.uw'G.ڎOngVw砛4n騧ꬷ.n{-o'7G/WozޢCu/o==@o>/oRQ+ H<_1'H [ڇAD9IB'9KDĒ6,, Mx07DɀDCȇ??ЈD! whD%3ԉ }(RQKa#Xb-O™o `˨'qe<h;QgTDARqL#P9H::" ߉\&C-Na x?"$b wQ e*[YHZVё&u)HR\fA ?ҏN\f&ge3yLҚה0OYYrtf.)(]ҁf8YH;2D$2 Ov^9>QNeJҔ?jP>6ԛL>I(.󛉬'? ̀Ft(4ѓVad&ϙЌ\g2IcRӥ0iK Ln̦:sL󧳼iHsGVJt3hcF.ԨiFGʑ6Le fsԔNMk9Rvħ-9ymzҗ4? bխjVjRXNL(.ؿs]C#GBդIXJ=/UyWzv%NkZӪVBe!YZUlINBMjڤ6K)[ UmwQԵ=dMyVwiqңlTFUjj[L*1`K[eŮAڵgwc_SuL2[J0ʽ6NU1_ Nt,GJؖp0- .i-&dB*>)ArI"%`3u|crflCu$YL:x̽<π ЈNɧ?O{'MJ[Z&\~!MF .ӌT Ƥ~wN %{Puj5!li^!ӳ2Lj_x1j][6C#L2/%c T/eykb[px P}Aky9ٚ+.}o%p@VЂfsܣst1}jzG -iU0Ta ԙ| _[ T+]Tw)aԘiN߄ȶ4? 6tbD *XqE)ZF&4$J*1v cK/At&I#qc͜3agK<{NtjTS 4x BX&Bc S(Z5]tۛoֵ -]y%J_98dқyu2`Ub#wy21ŋxE}4cJuiل3vbu&;eOJmzo{PөW偔3ozxɗ7yͳW^<)W+x޽;/@ J+;% -02>.E 3$H+绯K|e+۰iܑ}q?SGerqKjњ|,&|6$l'!!.G,I##tO˗,.7k7 <\H"I'{B =51AOH\NMC-%JA1uT7J:D/sISCTdX{N0TQA00 t 6+ػX/iӫ\}ZvŔ N0ljU|HZ"1]lD]g9lm5PjQkך_lWy-6^a̯L2CR+4,8muՔ+ 9QIWڏ\MUNW=Oh?EM%Z^Q#Ur_ gyi}i^*Nau`}^ȖNgFvn1w؍{ڬkY>o}5wnQ޻l^~V\-ۚM[HURL4N_u=yv׉EA>s]5\!+w{h$xWsߞɚ@/z볇_}?۟/x0@zⷢ $.R] дp-z: 8YJ'X5_Hn:ܜt79Md[#CH*V'J RZTy5.eR xMk4U:X8kbvE)Y_JԄ"͈B8lix*.97<WA:p'|ʑ7\ #G7qa^s9ysAЉ^,΋ml,h D!Ĉ'Rh"ƌ7r#Ȑ"G,*S\%̗/ND&Dp2t8p!>M-j(ҤJ2m:Rg̨2RU3hOy Ʉ` JpӴjײm-܆AҭjwUgRzЫ_yk0Ċ#Zݘf kM˖j1ТGv2xr6ksج%sҺw;lw'<;9MUmnެ3'ϩ(Ǔ//.zNq7o>_]E$w9 *z9ҁVD`wYEXj[=-۴q")-"18#5x#9#=#A 9d^ן45$QJ9%UZy%Yj%]z%a9&e j9w q9'uy'y'}' :(z(*(7`}H:)Zz)j)z):*z**q8+ + ;,X,*k:,-ZZj-Թ-Q{yz\ߢ.ԨvnNkًܱ 'kޭ>??W??(2| #( RT;junit4-4.11/doc/testinfected/IMG00002.GIF0000644000175000017500000001542612050524441016764 0ustar ebourgebourgGIF89a6@ @ @@@@@``@``@@@@ @ @ @ @@ @ @ ` `@ ` ` @ @ @ @ @@@@@@ @ @@ @ @@@@@@@@@@`@`@@`@`@@@@@@@@@@@@@@@@@@@@``@``` ` @` ` `@`@@`@`@````@``````@````@````@````@``@ @ @@@@@``@``@@@@@ @ @@@@@``@``@@@@@ @ @@@@@``@``@@@@@ @ @@@@@``@``@@@@!,6 H*\ȰÇ#JHŋ3jܨmBIɓ(S\ɲ˗0cʜI͛8s#H[@ JѣH*]ʴӧPJJիXV֯`ÊKٳhri+۷pʝKݻx˷߿ L6@IpA,˘3k̹|dd^ͺװ5@nEwz;dGN?2\ܶ=sZ྅ $atC"OJ}{ѥwع[+>p~whށ&zIރ={BQ8}֘~q 蘀 #Ɨ "`QDآ^(uoq_@^%~G"PQ/PPiLaޙs9`hhݏkQiy5z0ʘWI!rv1ʦi饖MiTC][ !YZJfJ&͉*j`i~:afhߛ!gRsNNV[`*,VKBVlҚv+:`\{XJ*k;zz7ߍHwn"lvwܱG̱sz,sn͜-K/wDmt_BL7PG=RWmXg58n`-]mhSepǍurmxcEw|{-x'xԇ/㐃ԕn]#5y35F~_gκS#c^Fz4N:V:o<̧ީ i+:~:Л?߻Zϭ??>.u_7:)P~ l'/;UP~d` |A9p~`1H児۠٣ gBrp4/ nЁ+ PzU_8D0[H/H@6bx7vqpK`iІZc =Y3|G_{!X;mr̤&Mzi$(GIʭLNV,|,gyXl-s^.싾 0L.L2f:Ќ4IjF1^ Nl׸ 8IrL:yNd#鉋)*m̧>Osk 7驛~MBuOti$&tEZͨA*-"h4JҒ-(<RtCIEC2Sk6(ͩNҫT-/eZQس,ANԚ4)4**.SGjҴ^G*VU$5mHZV6pUVrUF֏)UނUdb `kVug=aظ:'h ʩjEXאSi`&5mI ־8[+EQ(yE8%i AkXYK^h =5%8$mE[l%,qKMs׻SK Pwc ^vEq_8=}|gasaįZ[^I2]ζ .YEn \ر$P)dTHLK7NzZ^ūL*ۄM*촬V_U,^-[6N;3,R7pnɒzMB 5=2#ΐv3Ii44-wNӞ5(A-RgԦN5 ml,h „ 2l!Ĉ'Rh"ƌ7r옱 =,i$ʔ*Wlȁ.gҬi&Μ:'РBSfѤJ2mJӨRRj*CZZ+ؙX0X6,ڴj 铬Yen5;W-\ 7/k,޼t&1Ɛ Sly["8g_.mrf'nbҰOӮ6hͬ?/;§⎫z7ޑAC=9n-b;9o7oᄄO>t (txx.D : J8!Zx!j!z!!!u]G8)"-"18#5x#9#=#%Zu"Ey$I*$M(dUD:9%UZy%Y%URj%a9f\B(&mfJ%uy'Hy'S} z(I~h&J:)2e(j)RIrz*z:Ѩ(B:+*QC+~',Ɏ9,ŚtJ[%:[jFQܚ{nBP;*ۢ>k)"D0;D$1+pCx)1rjBS\Zl%r3̩38 -3ӳm3ADp-4֪f$AROo=5٩>}m^ Y6Zom,6U}7 >8~8+8;8KFrr YrB0Ry?CvWD魻zy.`_ /_^+];\KoZ[OYkV{mKFŞDõM}uƕ^9tG;QY?.w c," v#AL!# K@ͤ51zRh ѧB p#Ck(}q QRA7IDob~A]ڲș[f9h۵EMΛ_&[wSW'ͼ`/Gճ8TWcn{_.oiT9B_;ހ}>R a^~݄-C'V\7]s",$f*gMX vfV|-RhBiED %PdT9eXxe\ҷe`ed:6fhYlp)tix|矀*( fx&袌6裐F*餔Vj饘fա*ꨤjꩨꪬ꫰*무j뭮zj +k챳j6F+*[d--ߊږkz;қn v mSWؾ.,* ꮸ믩BL.+k2lmx.|q6/1 L4O7lr+'ײB/wsrPT GLߨ/Nӄ?Noyފ~{3N;G0E~ˮZ7\n{K_{?;k >ߚ>u/|旳٘'玾çKUڧ= uMl]>ɏ~\9mx[8?0~ˠ6:wΓY w/p[lH#_Sh|]4jX*6CZ {K!ט8-krW'zc&D0Z(GgXVl 5>rڣRXF:򑐌Cm̤&7Nz (GIRL*)>&,gIZ%)Y,$ 0Ibe\`"Ќ4YLe Œ̦6nnϚA7Irs8vJO zДIX -z Mh' ~Jə D#2n顾dD'ю޳HGJҒ(-)HzPz0='HyQ8Lo@Py_fsͩRZ D$IQ5zT&Xj-wLUUJֲr}IM[:Vj 5l+\WD*ULs-#E%jCYJ~e_+d'ͤ,\fU=+SU]ig{ZBHO!"XV nNQܺg yQG{Y:>Y–.G{#Mo[j.N[X.MKUlg`AmSaC!F8bE1fԸcGA^hmTeKDhr`˙!qԹgO?n$GQ&ETiSOڊi3P7fպkW_Z%YeYf^ZS-XoƕUl6wջo_|SR)3\Ç'V-I!G:αzwޯg_?mǗz}{׿p}񃏿 ˿ p%i! ) 1P 9Lim!Q" Dn"{$15#TS7dtO=ųK1qSsTRW<YCFGYMPXQԂ"a Z=Usز҄YavKYVZq}=W7UKuscSuJ7s6{ö]veQUt]`W~ex)N_Θĉ+ۇǭXٌd`|=f$|YiqYg<猷y{[裑NZ饙n駛YꅗWӖAZ뭹[챹\L[mDx[nܞn;ռot[ 2O\q_!W)<-\[A]I/O751o%a]iq]61-.'tBor%e^uuȡGų/v@w%eiH[2}7w(Xcߖg?X,;UP%9Ū ā(A B0 9ATUw`,  ł!zC, IC#Lb _8,D%TJ#ρAd%1d$#hF(QBtcTq`dH1K wHB(F>fІptA+1٢YH/R,$ CM1T# ILna%=GEr$J\*r,-Q 'URp$ULLrHl ?SfSCjL=6|T7IaRdb#3|:DϢٓ§~_2BPXԴPnRz<{QnG3:,I9T*eKRts2M)gStq:O SoB%QfT.mSUNUUIm]WVUk3Yњ;junit4-4.11/doc/testinfected/logo.gif0000644000175000017500000000170412050524441017060 0ustar ebourgebourgGIF89a& ! ,&@HD#B(1 b(ѠE C,Ñ(KrHE/3tQI(mn̙Seŏ?<9TC'4h͖JD0hTX{N%!ή jҊ)wz'Χ3R-JnۥbE.W{;գU~D;q@;junit4-4.11/doc/testinfected/IMG00001.GIF0000644000175000017500000001443212050524441016757 0ustar ebourgebourgGIF89a6@ @ @@@@@``@``@@@@ @ @ @ @@ @ @ ` `@ ` ` @ @ @ @ @@@@@@ @ @@ @ @@@@@@@@@@`@`@@`@`@@@@@@@@@@@@@@@@@@@@``@``` ` @` ` `@`@@`@`@````@``````@````@````@````@``@ @ @@@@@``@``@@@@@ @ @@@@@``@``@@@@@ @ @@@@@``@``@@@@@ @ @@@@@``@``@@@@!,6 H*\ȰÇ#JHŋ3jܨmBIɓ(S\ɲ˗0cʜI͛8s#H[@ JѣH*]ʴӧPJJիXV֯`ÊKٳhri+۷pʝKݻx˷߿ L6@IpA,˘3k̹|dd^ͺװ5@nEwz;dGN?2\ܶ=sZ྅ $atC"OJ}{ѥwع[+>p~whށ&zIރ={BQ8}֘~q 蘀 #Ɨ "`QDآ^(uoq_@^%~G"PQ/PPiLaޙs9`hhݏkQiy5z0ʘWI!rv1ʦi饖MiTC][ !YZJfJ&͉*j`i~:afhߛ!gRsNNV[`*,VKBVlҚv+:`\{XJ*k;zz7ߍHwn"lvwܱG̱sz,sn͜-K/wDmt_BL7PG=RWmXg58n`-]mhSepǍurmxcEw|{-x'xԇ/㐃ԕn]#5y35F~_gκS#c^Fz4N:V:o<̧ީ i+:~:Л?߻Zϭ??>.u_7:)P~ l'/;UP~d` |A9p~`1H児۠٣ gBrp4/ nЁ+ PzU_8D0[H/H@6bx7vqpK`iІZc =Y3|G_{!X;mr̤&Mzi$(GIʭLNV,|,gyXl-s^.싾 0L.L2f:Ќ4IjF1^ Nl׸ 8IrL:yNd#鉋)*m̧>Osk 7驛~MBuO݋O֋(D'*ъR$&tEz A5D,A3$Җ0m Iд(hPѐ&MLJ~j&NwzԂ="6XISeCt(5ݡ rӁɚ%XVsڢ˵`]{ ,xƱ Ko⽎n 0ʖN/Ή#{|Ҧ-gFHzr~*& 4aSϺs.|*w4ßCr*fڮlѿY/q3/oj??@bM7WB$0ؠBRXbrءRוz$p+آ/3X7☣;أ?XU'YG"K2dBVESRYWbPR%_cf%q *"k٦ohT^Yw≤Qљ{:է"hfBj*2(SRh)E2)ꑨꡧJjGZu'z.:"엹I*F2`-i-DNA {mr.8{бF4{.11" ˭[ܰ)PkPmCk˱ɶzl <2|̥z\ ~w'9vE D(`6<3F)P4̙v| H|Y9`sz㜊 oB!qv̘J҇~sr!OMs4x&$Τ}Hlu&Ѕ\TM_Lp&Tb \I0}la"{++pbYA8)Y)*QD-^ĘQF3OG%MDRJ-[9L5męSC#wTP6{,TRMuUTU-BUVEvVX_ɞEVmAkݾ+m\u{W^eCXy F B隃9dq'0Sq?n 0;tk1ȔBH#/"H%l(I&')Ē+䒾-/$ӱ1D0`M7߄3N9礳N;3O=O?4PAd05C4QEeQG4RI'RK/4SM70'TQG%TSOE5UUWeUW_5VYgV[ouSCd&\6Xa%XcUW@EYg6Zi-U٪6[mh ׅ|\sE7QMN\U7^yXvr7!x_+l&`7faMةbW/3fjcG&`}KfyOVJdgBMkghaNJf&ޛ٠fY*iBrjaZǥj65&hivZlFmmn;o ooɖk/YpFqE·~p/m6s?=t?WiP(u{?~goM/ly^'?~ /}tr義Ђ"va>PyD2h:Ё{adЄLa:Li^g(CHPz,uV-@ :цcbiA7QQ2{%Ģ Hc 7D&285U+Ilg`AmSaC!F8bE1fԸcGA^hm$QT%I,2fH7qԹgOG4ْhQ/i& OOF:jå$պ Jg2MXlYgNZM[oƕ;\Ie~Mo_-paÇ'Vx^]G<\1gn2A=ZagͧQs3iׯa56Wzcֽڿ˛xq}W,ϡCOãgמ{zn?^tw3'_kGٺ}}RO}]6  ,LPl!Ы( - 5= E,\M?s)Eb2FqQyB'Qk+߄$R% nB{),?//Ĭ*,3r0+)*(I6鬓=!3R3JTQA-H9%K3 UTN'RuRNtS2 QieSqEWUWeZ5-tVO{S`O]T^M/~%6Zi]fu?l_5kMem)+r\l˭yWmE7uU߅%1%X^bθaNz I.QNYYɍaxcpYy矁瘉fmn駡Zꩩ+F)˽X.{N[V;YM\ wǻޖ!\)1WI{I0>뜞|p}E(T+9%1C/|[=@/Qw` 텯W \`+_KGkx_! 5ABP S?|! ]ZJ8|aǹ/;T h{5t! DNOQ(Abш9>xB/qIXdXDn H@po"/b+U\hiϏģ!4r\$)=)y u}Lcb8ޑd(1yJFN҃BԊ5x2nRq$,'@)fЎ}< ^0mt#YJZҘd LiZll {xZ.Qa&] Test Infected:

JUnit Test Infected: Programmers Love Writing Tests


Note: this article describes JUnit 3.8.x.

Testing is not closely integrated with development. This prevents you from measuring the progress of development- you can't tell when something starts working or when something stops working. Using JUnit you can cheaply and incrementally build a test suite that will help you measure your progress, spot unintended side effects, and focus your development efforts.

Contents

The Problem

Every programmer knows they should write tests for their code. Few do. The universal response to "Why not?" is "I'm in too much of a hurry." This quickly becomes a vicious cycle- the more pressure you feel, the fewer tests you write. The fewer tests you write, the less productive you are and the less stable your code becomes. The less productive and accurate you are, the more pressure you feel.

Programmers burn out from just such cycles. Breaking out requires an outside influence. We found the outside influence we needed in a simple testing framework that lets us do a little testing that makes a big difference.

The best way to convince you of the value of writing your own tests would be to sit down with you and do a bit of development. Along the way, we would encounter new bugs, catch them with tests, fix them, have them come back, fix them again, and so on. You would see the value of the immediate feedback you get from writing and saving and rerunning your own unit tests.

Unfortunately, this is an article, not an office overlooking charming old-town Zürich, with the bustle of medieval commerce outside and the thump of techno from the record store downstairs, so we'll have to simulate the process of development. We'll write a simple program and its tests, and show you the results of running the tests. This way you can get a feel for the process we use and advocate without having to pay for our presence.

Example

As you read, pay attention to the interplay of the code and the tests. The style here is to write a few lines of code, then a test that should run, or even better, to write a test that won't run, then write the code that will make it run.

The program we write will solve the problem of representing arithmetic with multiple currencies. Arithmetic between single currencies is trivial, you can just add the two amounts. Simple numbers suffice. You can ignore the presence of currencies altogether.

Things get more interesting once multiple currencies are involved. You cannot just convert one currency into another for doing arithmetic since there is no single conversion rate- you may need to compare the value of a portfolio at yesterday's rate and today's rate.

Let's start simple and define a class Money to represent a value in a single currency. We represent the amount by a simple int. To get full accuracy you would probably use double or java.math.BigDecimal to store arbitrary-precision signed decimal numbers. We represent a currency as a string holding the ISO three letter abbreviation (USD, CHF, etc.). In more complex implementations, currency might deserve its own object.

class Money {
    private int fAmount;
    private String fCurrency;
    public Money(int amount, String currency) {
        fAmount= amount;
        fCurrency= currency;
    }

    public int amount() {
        return fAmount;
    }

    public String currency() {
        return fCurrency;
    }
}
When you add two Moneys of the same currency, the resulting Money has as its amount the sum of the other two amounts.
public Money add(Money m) {
    return new Money(amount()+m.amount(), currency());
}
Now, instead of just coding on, we want to get immediate feedback and practice "code a little, test a little, code a little, test a little". To implement our tests we use the JUnit framework. To write tests you need to get the latest copy JUnit (or write your own equivalent- it's not so much work).

JUnit defines how to structure your test cases and provides the tools to run them. You implement a test in a subclass of TestCase. To test our Money implementation we therefore define MoneyTest as a subclass of TestCase. In Java, classes are contained in packages and we have to decide where to put MoneyTest. Our current practice is to put MoneyTest in the same package as the classes under test. In this way a test case has access to the package private methods. We add a test method testSimpleAdd, that will exercise the simple version of Money.add() above. A JUnit test method is an ordinary method without any parameters.

public class MoneyTest extends TestCase {
    //
    public void testSimpleAdd() {
        Money m12CHF= new Money(12, "CHF");  // (1)
        Money m14CHF= new Money(14, "CHF");        
        Money expected= new Money(26, "CHF");
        Money result= m12CHF.add(m14CHF);    // (2)
        Assert.assertTrue(expected.equals(result));     // (3)
    }
}
The testSimpleAdd() test case consists of:
  1. Code which creates the objects we will interact with during the test. This testing context is commonly referred to as a test's fixture. All we need for the testSimpleAdd test are some Money objects.
  2. Code which exercises the objects in the fixture.
  3. Code which verifies the result.
Before we can verify the result we have to digress a little since we need a way to test that two Money objects are equal. The Java idiom to do so is to override the method equals defined in Object. Before we implement equals let's a write a test for equals in MoneyTest.
public void testEquals() {
    Money m12CHF= new Money(12, "CHF");
    Money m14CHF= new Money(14, "CHF");

    Assert.assertTrue(!m12CHF.equals(null));
    Assert.assertEquals(m12CHF, m12CHF);
    Assert.assertEquals(m12CHF, new Money(12, "CHF")); // (1)
    Assert.assertTrue(!m12CHF.equals(m14CHF));
}
The equals method in Object returns true when both objects are the same. However, Money is a value object. Two Monies are considered equal if they have the same currency and value. To test this property we have added a test (1) to verify that Monies are equal when they have the same value but are not the same object.

Next let's write the equals method in Money:

public boolean equals(Object anObject) {
    if (anObject instanceof Money) {
        Money aMoney= (Money)anObject;
        return aMoney.currency().equals(currency())
            && amount() == aMoney.amount();
    }
    return false;
}
Since equals can receive any kind of object as its argument we first have to check its type before we cast it as a Money. As an aside, it is a recommended practice to also override the method hashCode whenever you override method equals. However, we want to get back to our test case.

With an equals method in hand we can verify the outcome of testSimpleAdd. In JUnit you do so by a calling Assert.assertTrue, which triggers a failure that is recorded by JUnit when the argument isn't true. Since assertions for equality are very common, there is also an Assert.assertEquals convenience method. In addition to testing for equality with equals, it reports the printed value of the two objects in the case they differ. This lets us immediately see why a test failed in a JUnit test result report. The value a string representation created by the toString converter method. There are other asertXXXX variants not discussed here.

Now that we have implemented two test cases we notice some code duplication for setting-up the tests. It would be nice to reuse some of this test set-up code. In other words, we would like to have a common fixture for running the tests. With JUnit you can do so by storing the fixture's objects in instance variables of your TestCase subclass and initialize them by overridding the setUp method. The symmetric operation to setUp is tearDown which you can override to clean up the test fixture at the end of a test. Each test runs in its own fixture and JUnit calls setUp and tearDown for each test so that there can be no side effects among test runs.

public class MoneyTest extends TestCase {
    private Money f12CHF;
    private Money f14CHF;   

    protected void setUp() {
        f12CHF= new Money(12, "CHF");
        f14CHF= new Money(14, "CHF");
    }
}
We can rewrite the two test case methods, removing the common setup code:
public void testEquals() {
    Assert.assertTrue(!f12CHF.equals(null));
    Assert.assertEquals(f12CHF, f12CHF);
    Assert.assertEquals(f12CHF, new Money(12, "CHF"));
    Assert.assertTrue(!f12CHF.equals(f14CHF));
}

public void testSimpleAdd() {
    Money expected= new Money(26, "CHF");
    Money result= f12CHF.add(f14CHF);
    Assert.assertTrue(expected.equals(result));
}
Two additional steps are needed to run the two test cases:
  1. define how to run an individual test case,
  2. define how to run a test suite.
JUnit supports two ways of running single tests:
  • static
  • dynamic
In the static way you override the runTest method inherited from TestCase and call the desired test case. A convenient way to do this is with an anonymous inner class. Note that each test must be given a name, so you can identify it if it fails.
TestCase test= new MoneyTest("simple add") {
    public void runTest() {
        testSimpleAdd();
    }
};
A template method[1] in the superclass will make sure runTest is executed when the time comes.

The dynamic way to create a test case to be run uses reflection to implement runTest. It assumes the name of the test is the name of the test case method to invoke. It dynamically finds and invokes the test method. To invoke the testSimpleAdd test we therefore construct a MoneyTest as shown below:

TestCase test= new MoneyTest("testSimpleAdd");
The dynamic way is more compact to write but it is less static type safe. An error in the name of the test case goes unnoticed until you run it and get a NoSuchMethodException. Since both approaches have advantages, we decided to leave the choice of which to use up to you.

As the last step to getting both test cases to run together, we have to define a test suite. In JUnit this requires the definition of a static method called suite. The suite method is like a main method that is specialized to run tests. Inside suite you add the tests to be run to a TestSuite object and return it. A TestSuite can run a collection of tests. TestSuite and TestCase both implement an interface called Test which defines the methods to run a test. This enables the creation of test suites by composing arbitrary TestCases and TestSuites. In short TestSuite is a Composite [1]. The code below illustrates the creation of a test suite with the dynamic way to run a test.

public static Test suite() {
    TestSuite suite= new TestSuite();
    suite.addTest(new MoneyTest("testEquals"));
    suite.addTest(new MoneyTest("testSimpleAdd"));
    return suite;
}
Since JUnit 2.0 there is an even simpler dynamic way. You only pass the class with the tests to a TestSuite and it extracts the test methods automatically.

public static Test suite() {
    return new TestSuite(MoneyTest.class);
}

Here is the corresponding code using the static way.

public static Test suite() {
    TestSuite suite= new TestSuite();
    suite.addTest(
        new MoneyTest("money equals") {
            protected void runTest() { testEquals(); }
        }
    );
    
    suite.addTest(
        new MoneyTest("simple add") {
            protected void runTest() { testSimpleAdd(); }
        }
    );
    return suite;
}
Now we are ready to run our tests. JUnit comes with a graphical  interface to run tests. Type the name of your test class in the field at the top of the window. Press the Run button. While the test is run JUnit shows its progress with a progress bar below the input field. The bar is initially green but turns into red as soon as there is an unsuccessful test. Failed tests are shown in a list at the bottom. Figure 1 shows the TestRunner window after we run our trivial test suite.

Figure 1: A Successful Run

After having verified that the simple currency case works we move on to multiple currencies. As mentioned above the problem of mixed currency arithmetic is that there isn't a single exchange rate. To avoid this problem we introduce a MoneyBag which defers exchange rate conversions. For example adding 12 Swiss Francs to 14 US Dollars is represented as a bag containing the two Monies 12 CHF and 14 USD. Adding another 10 Swiss francs gives a bag with 22 CHF and 14 USD. We can later evaluate a MoneyBag with different exchange rates.

A MoneyBag is represented as a list of Monies and provides different constructors to create a MoneyBag. Note, that the constructors are package private since MoneyBags are created behind the scenes when doing currency arithmetic.

class MoneyBag {
    private Vector fMonies= new Vector();

    MoneyBag(Money m1, Money m2) {
        appendMoney(m1);
        appendMoney(m2);
    }

    MoneyBag(Money bag[]) {
        for (int i= 0; i < bag.length; i++)
            appendMoney(bag[i]);
    }
}
The method appendMoney is an internal helper method that adds a Money to the list of Moneys and takes care of consolidating Monies with the same currency. MoneyBag also needs an equals method together with a corresponding test. We skip the implementation of equals and only show the testBagEquals method. In a first step we extend the fixture to include two MoneyBags.
protected void setUp() {
    f12CHF= new Money(12, "CHF");
    f14CHF= new Money(14, "CHF");
    f7USD=  new Money( 7, "USD");
    f21USD= new Money(21, "USD");
    fMB1= new MoneyBag(f12CHF, f7USD);
    fMB2= new MoneyBag(f14CHF, f21USD);
}
With this fixture the testBagEquals test case becomes:
public void testBagEquals() {
    Assert.assertTrue(!fMB1.equals(null));
    Assert.assertEquals(fMB1, fMB1);
    Assert.assertTrue(!fMB1.equals(f12CHF));
    Assert.assertTrue(!f12CHF.equals(fMB1));
    Assert.assertTrue(!fMB1.equals(fMB2));
}
Following "code a little, test a little" we run our extended test with JUnit and verify that we are still doing fine. With MoneyBag in hand, we can now fix the add method in Money.
public Money add(Money m) {
    if (m.currency().equals(currency()) )
        return new Money(amount()+m.amount(), currency());
    return new MoneyBag(this, m);
}
As defined above this method will not compile since it expects a Money and not a MoneyBag as its return value. With the introduction of MoneyBag there are now two representations for Moneys which we would like to hide from the client code. To do so we introduce an interface IMoney that both representations implement. Here is the IMoney interface:
interface IMoney {
    public abstract IMoney add(IMoney aMoney);
    //
}
To fully hide the different representations from the client we have to support arithmetic between all combinations of Moneys with MoneyBags. Before we code on, we therefore define a couple more test cases. The expected MoneyBag results use the convenience constructor shown above, initializing a MoneyBag from an array.
public void testMixedSimpleAdd() { 
    // [12 CHF] + [7 USD] == {[12 CHF][7 USD]} 
    Money bag[]= { f12CHF, f7USD }; 
    MoneyBag expected= new MoneyBag(bag); 
    Assert.assertEquals(expected, f12CHF.add(f7USD)); 
}
The other tests follow the same pattern:
  • testBagSimpleAdd - to add a MoneyBag to a simple Money
  • testSimpleBagAdd - to add a simple Money to a MoneyBag
  • testBagBagAdd - to add two MoneyBags
  • Next, we extend our test suite accordingly:
    public static Test suite() {
        TestSuite suite= new TestSuite();
        suite.addTest(new MoneyTest("testMoneyEquals"));
        suite.addTest(new MoneyTest("testBagEquals"));
        suite.addTest(new MoneyTest("testSimpleAdd"));
        suite.addTest(new MoneyTest("testMixedSimpleAdd"));
        suite.addTest(new MoneyTest("testBagSimpleAdd"));
        suite.addTest(new MoneyTest("testSimpleBagAdd"));
        suite.addTest(new MoneyTest("testBagBagAdd"));
        return suite;
    }
    Having defined the test cases we can start to implement them. The implementation challenge here is dealing with all the different combinations of Money with MoneyBag. Double dispatch [2] is an elegant way to solve this problem. The idea behind double dispatch is to use an additional call to discover the kind of argument we are dealing with. We call a method on the argument with the name of the original method followed by the class name of the receiver. The add method in Money and MoneyBag becomes:
    class Money implements IMoney {
        public IMoney add(IMoney m) {
            return m.addMoney(this);
        }
        //
    }
    class MoneyBag implements IMoney {
        public IMoney add(IMoney m) {
            return m.addMoneyBag(this);
        }
        //
    }
    In order to get this to compile we need to extend the interface of IMoney with the two helper methods:
    interface IMoney {
    //
        IMoney addMoney(Money aMoney);
        IMoney addMoneyBag(MoneyBag aMoneyBag);
    }
    To complete the implementation of double dispatch, we have to implement these methods in Money and MoneyBag. This is the implementation in Money.
    public IMoney addMoney(Money m) {
        if (m.currency().equals(currency()) )
            return new Money(amount()+m.amount(), currency());
        return new MoneyBag(this, m);
    }
    
    public IMoney addMoneyBag(MoneyBag s) {
        return s.addMoney(this);
    }
    Here is the implemenation in MoneyBag which assumes additional constructors to create a MoneyBag from a Money and a MoneyBag and from two MoneyBags.
    public IMoney addMoney(Money m) {
        return new MoneyBag(m, this);
    }
    
    public IMoney addMoneyBag(MoneyBag s) {
        return new MoneyBag(s, this);
    }
    We run the tests, and they pass. However, while reflecting on the implementation we discover another interesting case. What happens when as the result of an addition a MoneyBag turns into a bag with only one Money? For example, adding -12 CHF to a Moneybag holding 7 USD and 12 CHF results in a bag with just 7 USD. Obviously, such a bag should be equal with a single Money of 7 USD. To verify the problem let's implement a test case and run it.
    public void testSimplify() {
        // {[12 CHF][7 USD]} + [-12 CHF] == [7 USD]
        Money expected= new Money(7, "USD");
        Assert.assertEquals(expected, fMB1.add(new Money(-12, "CHF")));
    }
    When you are developing in this style you will often have a thought and turn immediately to writing a test, rather than going straight to the code.

    It comes to no surprise that our test run ends with a red progress bar indicating the failure. So we fix the code in MoneyBag to get back to a green state.

    public IMoney addMoney(Money m) {
        return (new MoneyBag(m, this)).simplify();
    }
    
    public IMoney addMoneyBag(MoneyBag s) {
        return (new MoneyBag(s, this)).simplify();
    }
    
    private IMoney simplify() {
        if (fMonies.size() == 1)
            return (IMoney)fMonies.firstElement()
        return this;
    }
    Now we run our tests again and voila we end up with green.

    The code above solves only a small portion of the multi-currency arithmetic problem. We have to represent different exchange rates, print formatting, and the other arithmetic operations, and do it all with reasonable speed. However, we hope you can see how you could develop the rest of the objects one test at a time- a little test, a little code, a little test, a little code.

    In particular, review how in the development above:

    • We wrote the first test, testSimpleAdd, immediately after we had written add(). In general, your development will go much smoother if you write tests a little at a time as you develop. It is at the moment that you are coding that you are imagining how that code will work. That's the perfect time to capture your thoughts in a test.
    • We refactored the existing tests, testSimpleAdd and testEqual, as soon as we introduced the common setUp code. Test code is just like model code in working best if it is factored well. When you see you have the same test code in two places, try to find a way to refactor it so it only appears once.
    • We created a suite method, then extended it when we applied Double Dispatch. Keeping old tests running is just as important as making new ones run. The ideal is to always run all of your tests. Sometimes that will be too slow to do 10 times an hour. Make sure you run all of your tests at least daily.
    • We created a new test immediately when we thought of the requirement that a one element MoneyBag should just return its element. It can be difficult to learn to switch gears like this, but we have found it valuable. When you are struck by an idea of what your system should do, defer thinking about the implementation. Instead, first write the test. Then run it (you never know, it might already work). Then work on the implementation.

    Testing Practices

    Martin Fowler makes this easy for you. He says, "Whenever you are tempted to type something into a print statement or a debugger expression, write it as a test instead." At first you will find that you have to create a new fixtures all the time, and testing will seem to slow you down a little. Soon, however, you will begin reusing your library of fixtures and new tests will usually be as simple as adding a method to an existing TestCase subclass.

    You can always write more tests. However, you will quickly find that only a fraction of the tests you can imagine are actually useful. What you want is to write tests that fail even though you think they should work, or tests that succeed even though you think they should fail. Another way to think of it is in cost/benefit terms. You want to write tests that will pay you back with information.

    Here are a couple of the times that you will receive a reasonable return on your testing investment:

    • During Development- When you need to add new functionality to the system, write the tests first. Then, you will be done developing when the test runs.
    • During Debugging- When someone discovers a defect in your code, first write a test that will succeed if the code is working. Then debug until the test succeeds.
    One word of caution about your tests. Once you get them running, make sure they stay running. There is a huge difference between having your suite running and having it broken. Ideally, you would run every test in your suite every time you change a method. Practically, your suite will soon grow too large to run all the time. Try to optimize your setup code so you can run all the tests. Or, at the very least, create special suites that contain all the tests that might possibly be affected by your current development. Then, run the suite every time you compile. And make sure you run every test at least once a day: overnight, during lunch, during one of those long meetings.

    Conclusion

    This article only scratches the surface of testing. However, it focuses on a style of testing that with a remarkably small investment will make you a faster, more productive, more predictable, and less stressed developer.

    Once you've been test infected, your attitude toward development is likely to change. Here are some of the changes we have noticed:

    There is a huge difference between tests that are all running correctly and tests that aren't. Part of being test infected is not being able to go home if your tests aren't 100%. If you run your suite ten or a hundred times an hour, though, you won't be able to create enough havoc to make you late for supper.

    Sometimes you just won't feel like writing tests, especially at first. Don't. However, pay attention to how much more trouble you get into, how much more time you spend debugging, and how much more stress you feel when you don't have tests. We have been amazed at how much more fun programming is and how much more aggressive we are willing to be and how much less stress we feel when we are supported by tests. The difference is dramatic enough to keep us writing tests even when we don't feel like it.

    You will be able to refactor much more aggressively once you have the tests. You won't understand at first just how much you can do, though. Try to catch yourself saying, "Oh, I see, I should have designed this thus and so. I can't change it now. I don't want to break anything." When you say this, save a copy of your current code and give yourself a couple of hours to clean up. (This part works best you can get a buddy to look over your shoulder while you work.) Make your changes, all the while running your tests. You will be surprised at how much ground you can cover in a couple of hours if you aren't worrying every second about what you might be breaking.

    For example, we switched from the Vector-based implementation of MoneyBag to one based on HashTable. We were able to make the switch very quickly and confidently because we had so many tests to rely on. If the tests all worked, we were sure we hadn't changed the answers the system produced at all.

    You will want to get the rest of your team writing tests. The best way we have found to spread the test infection is through direct contact. The next time someone asks you for help debugging, get them to talk about the problem in terms of a fixture and expected results. Then say, "I'd like to write down what you just told me in a form we can use." Have them watch while you write one little test. Run it. Fix it. Write another. Pretty soon they will be writing their own.

    So- give JUnit a try. If you make it better, please send us the changes so we can spread them around. Our next article will double click on the JUnit framework itself. We will show you how it is constructed, and talk a little about our philosophy of framework development.

    We would like to thank Martin Fowler, as good a programmer as any analyst can ever hope to be, for his helpful comments in spite of being subjected to early versions of JUnit.

    References

    1. Gamma, E., et al. Design Patterns: Elements of Reusable Object-Oriented Software, Addison-Wesley, Reading, MA, 1995
    2. Beck, K. Smalltalk Best Practice Patterns, Prentice Hall, 1996

    junit4-4.11/doc/cookstour/0000755000175000017500000000000012050524441014776 5ustar ebourgebourgjunit4-4.11/doc/cookstour/cookstour.htm0000644000175000017500000011255712050524441017553 0ustar ebourgebourg JUnit: A Cooks Tour

    JUnit A Cook's Tour


    Note: this article is based on JUnit 3.8.x.

    1. Introduction

    In an earlier article (see Test Infected: Programmers Love Writing Tests, Java Report, July 1998, Volume 3, Number 7), we described how to use a simple framework to write repeatable tests. In this article, we will take a peek under the covers and show you how the framework itself is constructed.

    We carefully studied the JUnit framework and reflected on how we constructed it. We found lessons at many different levels. In this article we will try communicate them all at once, a hopeless task, but at least we will do it in the context of showing you the design and construction of a piece of software with proven value.

    We open with a discussion of the goals of the framework. The goals will reappear in many small details during the presentation of the framework itself. Following this, we present the design and implementation of the framework. The design will be described in terms of patterns (surprise, surprise), the implementation as a literate program. We conclude with a few choice thoughts about framework development.

    2. Goals

    What are the goals of JUnit?

    First, we have to get back to the assumptions of development. If a program feature lacks an automated test, we assume it doesnt work. This seems much safer than the prevailing assumption, that if a developer assures us a program feature works, then it works now and forever.

    From this perspective, developers arent done when they write and debug the code, they must also write tests that demonstrate that the program works. However, everybody is too busy, they have too much to do, they dont have enough time, to screw around with testing. I have too much code to write already, how am I supposed write test code, too? Answer me that, Mr. Hard-case Project Manager.

    So, the number one goal is to write a framework within which we have some glimmer of hope that developers will actually write tests. The framework has to use familiar tools, so there is little new to learn. It has to require no more work than absolutely necessary to write a new test. It has to eliminate duplicated effort.

    If this was all tests had to do, you would be done just by writing expressions in a debugger. However, this isnt sufficient for testing. Telling me that your program works now doesnt help me, because it doesnt assure me that your program will work one minute from now after I integrate, and it doesnt assure me that your program will still work in five years, when you are long gone.

    So, the second goal of testing is creating tests that retain their value over time. Someone other than the original author has to be able to execute the tests and interpret the results. It should be possible to combine tests from various authors and run them together without fear of interference.

    Finally, it has to be possible to leverage existing tests to create new ones. Creating a setup or fixture is expensive and a framework has to enable reusing fixtures to run different tests. Oh, is that all?

    3. The Design of JUnit

    The design of JUnit will be presented in a style first used in (see "Patterns Generate Architectures", Kent Beck and Ralph Johnson, ECOOP 94). The idea is to explain the design of a system by starting with nothing and applying patterns, one after another, until you have the architecture of the system. We will present the architectural problem to be solved, summarize the pattern that solves it, and then show how the pattern was applied to JUnit.

    3.1 Getting started- TestCase

    First we have to make an object to represent our basic concept, the TestCase. Developers often have tests cases in mind, but they realize them in many different ways-

    • print statements,
    • debugger expressions,
    • test scripts.
    If we want to make manipulating tests easy, we have to make them objects. This takes a test that was only implicit in the developers mind and makes it concrete, supporting our goal of creating tests that retain their value over time. At the same time, object developers are used to, well, developing with objects, so the decision to make tests into objects supports our goal of making test writing more inviting (or at least less imposing).

    The Command pattern (see Gamma, E., et al. Design Patterns: Elements of Reusable Object-Oriented Software, Addison-Wesley, Reading, MA, 1995) fits our needs quite nicely. Quoting from the intent, "Encapsulate a request as an object, thereby letting you queue or log requests" Command tells us to create an object for an operation and give it a method "execute". Here is the code for the class definition of TestCase:

    public abstract class TestCase implements Test {
       
    }
    Because we expect this class to be reused through inheritance, we declare it "public abstract". For now, ignore the fact that it implements the Test interface. For the purposes of our current design, you can think of TestCase as a lone class.

    Every TestCase is created with a name, so if a test fails, you can identify which test failed.

    public abstract class TestCase implements Test {
        private final String fName;

        public TestCase(String name) {
            fName= name;
        }

        public abstract void run();
           
    }

    To illustrate the evolution of JUnit, we use diagrams that show snapshots of the architecture. The notation we use is simple. It annotates classes with shaded boxes containing the associated pattern. When the role of the class in the pattern is obvious then only the pattern name is shown. If the role isnt clear then the shaded box is augmented by the name of the participant this class corresponds to. This notation minimizes the clutter in diagrams and was first shown in (see Gamma, E., Applying Design Patterns in Java, in Java Gems, SIGS Reference Library, 1997) Figure 1 shows this notation applied to TestCase. Since we are dealing with a single class and there can be no ambiguities just the pattern name is shown.

    Figure 1 TestCase applies Command

    3.2 Blanks to fill in- run()

    The next problem to solve is giving the developer a convenient "place" to put their fixture code and their test code. The declaration of TestCase as abstract says that the developer is expected to reuse TestCase by subclassing. However, if all we could do was provide a superclass with one variable and no behavior, we wouldnt be doing much to satisfy our first goal, making tests easier to write.

    Fortunately, there is a common structure to all tests- they set up a test fixture, run some code against the fixture, check some results, and then clean up the fixture. This means that each test will run with a fresh fixture and the results of one test cant influence the result of another. This supports the goal of maximizing the value of the tests.

    Template Method addresses our problem quite nicely. Quoting from the intent, "Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithms structure." This is exactly right. We want the developer to be able to separately consider how to write the fixture (set up and tear down) code and how to write the testing code. The execution of this sequence, however, will remain the same for all tests, no matter how the fixture code is written or how the testing code is written.

    Here is the template method:

    public void run() {
        setUp();
        runTest();
        tearDown();
    }
    The default implementations of these methods do nothing: protected void runTest() {
    }

    protected void setUp() {
    }

    protected void tearDown() {
    }

    Since setUp and tearDown are intended to be overridden but will be called by the framework we declare them as protected. The second snapshot of our tour is depicted in Figure 2.

    Figure 2 TestCase.run() applies Template Method

    3.3 Reporting results- TestResult

    If a TestCase runs in a forest, does anyone care about the result? Sure- you run tests to make sure they run. After the test has run, you want a record, a summary of what did and didnt work.

    If tests had equal chances of succeeding or failing, or if we only ever ran one test, we could just set a flag in the TestCase object and go look at the flag when the test completed. However, tests are (intended to be) highly asymmetric- they usually work. Therefore, we only want to record the failures and a highly condensed summary of the successes.

    The Smalltalk Best Practice Patterns (see Beck, K. Smalltalk Best Practice Patterns, Prentice Hall, 1996) has a pattern that is applicable. It is called Collecting Parameter. It suggests that when you need to collect results over several methods, you should add a parameter to the method and pass an object that will collect the results for you. We create a new object, TestResult, to collect the results of running tests.

    public class TestResult extends Object {
        protected int fRunTests;

        public TestResult() {
           fRunTests= 0;
        }
    }

    This simple version of TestResult only counts the number of tests run. To use it, we have to add a parameter to the TestCase.run() method and notify the TestResult that the test is running: public void run(TestResult result) {
        result.startTest(this);
        setUp();
        runTest();
        tearDown();
    }
    And the TestResult has to keep track of the number of tests run: public synchronized void startTest(Test test) {
        fRunTests++;
    }
    We declare the TestResult method startTest as synchronized so that a single TestResult can collect the results safely when the tests are run in different threads. Finally, we want to retain the simple external interface of TestCase, so we create a no-parameter version of run() that creates its own TestResult: public TestResult run() {
        TestResult result= createResult();
        run(result);
        return result;
    }

    protected TestResult createResult() {
        return new TestResult();
    }

    Figure 3 shows our next design snapshot.

    Figure 3: TestResult applies Collecting Parameter

    If tests always ran correctly, then we wouldnt have to write them. Tests are interesting when they fail, especially if we didnt expect them to fail. Whats more, tests can fail in ways that we expect, for example by computing an incorrect result, or they can fail in more spectacular ways, for example by writing outside the bounds of an array. No matter how the test fails we want to execute the following tests.

    JUnit distinguishes between failures and errors. The possibility of a failure is anticipated and checked for with assertions. Errors are unanticipated problems like an ArrayIndexOutOfBoundsException. Failures are signaled with an AssertionFailedError error. To distinguish an unanticipated error from a failure, failures are caught in an extra catch clause (1). The second clause (2) catches all other exceptions and ensures that our test run continues..

    public void run(TestResult result) {
        result.startTest(this);
        setUp();
        try {
            runTest();
        }
        catch (AssertionFailedError e) { //1
            result.addFailure(this, e);
        }

        catch (Throwable e) { // 2
            result.addError(this, e);
        }
        finally {
            tearDown();
        }
    }

    An AssertionFailedError is triggered by the assert methods provided by TestCase. JUnit provides a set of assert methods for different purposes. Here is the simplest one: protected void assertTrue(boolean condition) {
        if (!condition)
            throw new AssertionFailedError();
    }
    The AssertionFailedError is not meant to be caught by the client (a testing method inside a TestCase) but inside the Template Method TestCase.run(). We therefore derive AssertionFailedError from Error. public class AssertionFailedError extends Error {
        public AssertionFailedError () {}
    }
    The methods to collect the errors in TestResult are shown below: public synchronized void addError(Test test, Throwable t) {
        fErrors.addElement(new TestFailure(test, t));
    }

    public synchronized void addFailure(Test test, Throwable t) {
        fFailures.addElement(new TestFailure(test, t));
    }

    TestFailure is a little framework internal helper class to bind together the failed test and the signaled exception for later reporting. public class TestFailure extends Object {
        protected Test fFailedTest;
        protected Throwable fThrownException;
    }
    The canonical form of collecting parameter requires us to pass the collecting parameter to each method. If we followed this advice, each of the testing methods would require a parameter for the TestResult. This results in a "pollution" of these method signatures. As a benevolent side effect of using exceptions to signal failures we can avoid this signature pollution. A test case method, or a helper method called from it, can throw an exception without having to know about the TestResult. As a refresher here is a sample test method from our MoneyTest suite. It illustrates how a testing method doesnt have to know anything about a TestResult: public void testMoneyEquals() {
        assertTrue(!f12CHF.equals(null));
        assertEquals(f12CHF, f12CHF);
        assertEquals(f12CHF, new Money(12, "CHF"));
        assertTrue(!f12CHF.equals(f14CHF));
    }
    JUnit comes with different implementations of TestResult. The default implementation counts the number of failures and errors and collects the results. TextTestResult collects the results and presents them in a textual form. Finally, UITestResult is used by the graphical version of the JUnit Test Runner to update the graphical test status.

    TestResult is an extension point of the framework. Clients can define their own custom TestResult classes, for example, an HTMLTestResult reports the results as an HTML document.

    3.4 No stupid subclasses - TestCase again

    We have applied Command to represent a test. Command relies on a single method like execute() (called run() in TestCase) to invoke it. This simple interface allows us to invoke different implementations of a command through the same interface.

    We need an interface to generically run our tests. However, all test cases are implemented as different methods in the same class. This avoids the unnecessary proliferation of classes. A given test case class may implement many different methods, each defining a single test case. Each test case has a descriptive name like testMoneyEquals or testMoneyAdd. The test cases dont conform to a simple command interface. Different instances of the same Command class need to be invoked with different methods. Therefore our next problem is make all the test cases look the same from the point of view of the invoker of the test.

    Reviewing the problems addressed by available design patterns, the Adapter pattern springs to mind. Adapter has the following intent "Convert the interface of a class into another interface clients expect". This sounds like a good match. Adapter tells us different ways to do this. One of them is a class adapter, which uses subclassing to adapt the interface. For example, to adapt testMoneyEquals to runTest we implement a subclass of MoneyTest and override runTest to invoke testMoneyEquals.

    public class TestMoneyEquals extends MoneyTest {
        public TestMoneyEquals() { super("testMoneyEquals"); }
        protected void runTest () { testMoneyEquals(); }
    }
    The use of subclassing requires us to implement a subclass for each test case. This puts an additional burden on the tester. This is against the JUnit goal that the framework should make it as simple as possible to add a test case. In addition, creating a subclass for each testing method results in class bloat. Many classes with only a single method are not worth their costs and it will be difficult to come up with meaningful names.

    Java provides anonymous inner classes which provide an interesting Java-specific solution to the class naming problem. With anonymous inner classes we can create an Adapter without having to invent a class name:

    TestCase test= new MoneyTest("testMoneyEquals ") {
        protected void runTest() { testMoneyEquals(); }
    };
    This is much more convenient than full subclassing. It preserves compile-time type checking at the cost of some burden on the developer. Smalltalk Best Practice Patterns describes another solution for the problem of different instances behaving differently under the common heading of pluggable behavior. The idea is to use a single class which can be parameterized to perform different logic without requiring subclassing.

    The simplest form of pluggable behavior is the Pluggable Selector. Pluggable Selector stores a Smalltalk method selector in an instance variable. This idea is not limited to Smalltalk. It is also applicable to Java. In Java there is no notion of a method selector. However, the Java reflection API allows us to invoke a method from a string representing the methods name. We can use this feature to implement a pluggable selector in Java. As an aside, we usually dont use reflection in ordinary application code. In our case we are dealing with an infrastructure framework and it is therefore OK to wear the reflection hat.

    JUnit offers the client the choice of using pluggable selector or implementing an anonymous adapter class as shown above. To do so, we provide the pluggable selector as the default implementation of the runTest method. In this case the name of the test case has to correspond to the name of a test method. We use reflection to invoke the method as shown below. First we look up the Method object. Once we have the method object we can invoke it and pass its arguments. Since our test methods take no arguments we can pass an empty argument array:

    protected void runTest() throws Throwable {
        Method runMethod= null;
        try {
            runMethod= getClass().getMethod(fName, new Class[0]);
        } catch (NoSuchMethodException e) {
            assertTrue("Method \""+fName+"\" not found", false);
        }
        try {
            runMethod.invoke(this, new Class[0]);
        }
        // catch InvocationTargetException and IllegalAccessException
    }
    The JDK 1.1 reflection API only allows us to find public methods. For this reason you have to declare the test methods as public, otherwise you will get a NoSuchMethodException.

    Here is the next design snapshot, with Adapter and Pluggable Selector added.

    Figure 4: TestCase applies either Adapter with an anonymous inner class or Pluggable Selector

    3.5 Dont care about one or many - TestSuite

    To get confidence in the state of a system we need to run many tests. Up to this point JUnit can run a single test case and report the result in a TestResult. Our next challenge is to extend it so that it can run many different tests. This problem can be solved easily when the invoker of the tests doesnt have to care about whether it runs one or many test cases. A popular pattern to pull out in such a situation is Composite. To quote its intent "Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly." The point about part-whole hierarchies is of interest here. We want to support suites of suites of suites of tests.

    Composite introduces the following participants:

    • Component: declares the interface we want to use to interact with our tests.
    • Composite: implements this interface and maintains a collection of tests.
    • Leaf: represents a test case in a composition that conforms to the Component interface.
    The pattern tells us to introduce an abstract class which defines the common interface for single and composite objects. The primary purpose of the class is to define an interface. When applying Composite in Java we prefer to define an interface and not an abstract class. Using an interface avoids committing JUnit to a specific base class for tests. All that is required is that the tests conform to this interface. We therefore tweak the pattern description and introduce a Test interface: public interface Test {
        public abstract void run(TestResult result);
    }
    TestCase corresponds to a Leaf in Composite and implements this interface as we have seen above.

    Next, we introduce the Composite participant. We name the class TestSuite. A TestSuite keeps its child tests in a Vector:

    public class TestSuite implements Test {
        private Vector fTests= new Vector();
    }
    The run() method delegates to its children: public void run(TestResult result) {
        for (Enumeration e= fTests.elements(); e.hasMoreElements(); ) {
            Test test= (Test)e.nextElement();
            test.run(result);
        }
    }

    Figure 5: TestSuite applies Composite

    Finally, clients have to be able to add tests to a suite, they can do so with the method addTest:

    public void addTest(Test test) {
        fTests.addElement(test);
    }
    Notice how all of the above code only depends on the Test interface. Since both TestCase and TestSuite conform to the Test interface we can recursively compose suites of test suites. All developers can create their own TestSuites. We can run them all by creating a TestSuite composed of those suites.

    Here is an example of creating a TestSuite:

    public static Test suite() {
        TestSuite suite= new TestSuite();
        suite.addTest(new MoneyTest("testMoneyEquals"));
        suite.addTest(new MoneyTest("testSimpleAdd"));
    }
    This works fine, but it requires us to add all the tests to a suite manually. Early adopters of JUnit told us this was stupid. Whenever you write a new test case you have to remember to add it to a static suite() method, otherwise it will not be run. We added a convenience constructor to TestSuite which takes the test case class as an argument. Its purpose is to extract the test methods and create a suite containing them. The test methods must follow the simple convention that they start with the prefix "test" and take no arguments. The convenience constructor uses this convention, constructing the test objects by using reflection to find the testing methods. Using this constructor the above code is simplified to: public static Test suite() {
        return new TestSuite(MoneyTest.class);
    }
    The original way is still useful when you want to run a subset of the test cases only.

    3.6 Summary

    We are at the end of our cooks tour through JUnit. The following figure shows the design of JUnit at a glance explained with patterns.

    Figure 6: JUnit Patterns Summary

    Notice how TestCase, the central abstraction in the framework, is involved in four patterns. Pictures of mature object designs show this same "pattern density". The star of the design has a rich set of relationships with the supporting players.

    Here is another way of looking at all of the patterns in JUnit. In this storyboard you see an abstract representation of the effect of each of the patterns in turn. So, the Command pattern creates the TestCase class, the Template Method pattern creates the run method, and so on. (The notation of the storyboard is the notation of figure 6 with all the text deleted).

    Figure 7: JUnit Pattern Storyboard

    One point to notice about the storyboard is how the complexity of the picture jumps when we apply Composite. This is pictorial corroboration for our intuition that Composite is a powerful pattern, but that it "complicates the picture." It should therefore be used with caution.

    4. Conclusion

    To conclude, lets make some general observations:

    • Patterns

    • We found discussing the design in terms of patterns to be invaluable, both as we were developing the framework and as we try to explain it to others. You are now in a perfect position to judge whether describing a framework with patterns is effective. If you liked the discussion above, try the same style of presentation for your own system.
    • Pattern density

    • There is a high pattern "density" around TestCase, which is the key abstraction of JUnit. Designs with high pattern density are easier to use but harder to change. We have found that such a high pattern density around key abstractions is common for mature frameworks. The opposite should be true of immature frameworks - they should have low pattern density. Once you discover what problem you are really solving, then you can begin to "compress" the solution, leading to a denser and denser field of patterns where they provide leverage.
    • Eat your own dog food

    • As soon as we had the base unit testing functionality implemented, we applied it ourselves. A TestTest verifies that the framework reports the correct results for errors, successes, and failures. We found this invaluable as we continued to evolve the design of the framework. We found that the most challenging application of JUnit was testing its own behavior.
    • Intersection, not union

    • There is a temptation in framework development to include every feature you can. After all, you want to make the framework as valuable as possible. However, there is a counteracting force- developers have to decide to use your framework. The fewer features the framework has, the easier it is to learn, the more likely a developer will use it. JUnit is written in this style. It implements only those features absolutely essential to running tests- running suites of tests, isolating the execution of tests from each other, and running tests automatically. Sure, we couldnt resist adding some features but we were careful to put them into their own extensions package (test.extensions). A notable member of this package is a TestDecorator allowing execution of additional code before and after a test.
    • Framework writers read their code

    • We spent far more time reading the JUnit code than we spent writing it, and nearly as much time removing duplicate functionality as we spent adding new functionality. We experimented aggressively with the design, adding new classes and moving responsibility around in as many different ways as we could imagine. We were rewarded (and are still being rewarded) for our monomania by a continuous flow of insights into JUnit, testing, object design, framework development, and opportunities for further articles.
    The latest version of JUnit can be downloaded from http://www.junit.org.

    5. Acknowledgements

    Thanks to John Vlissides, Ralph Johnson, and Nick Edgar for careful reading and gentle correction. junit4-4.11/doc/cookstour/Image3.gif0000644000175000017500000000560212050524441016575 0ustar ebourgebourgGIF89aE,E@H*\ȰÇ#JHŋ3jȱǏ CIɓ(S\ɲ˗$P&͛8sO>jshСT:ϓOuJ2*UVj1+ת1f*!ٲ%ώe(ХmV)ݤE]H߿ LaHy 4Φ#+~8reƓ%CmE8ҡS=xQO3_^ٲK9${Ɖ#_{}^tֳޮ;wY|vSܷ@߃-| W_|7`~&_} oE%Z݆qa ~(b RșeI&-X+p4bZ\ը<@)DiH&L6$EE)TVyؓXx_ٌY6Zlz1%\f:ך8y=!IVwAjbgRcs~_P"OxN^(\hhXgF^eQifl娞vzggKզ*X8D$"u$hl[[IכWT` ˟˟[Y:T6lu͆X0tFJkvv/h5hf;20,4l8<@-DmtY.ѷݼ4,5Vڗɚs B>=dg3iv@rmdh*5\o]Jr~<ƹkiHR]{]l(!1>\%v:!^5.wH{ٳLqT(N|qm]5萣Ѓ }8qNݱB=#!Ro]7ܽ=߷?~>Uב݇arN?| v-V֡#Ru:  )p^zPJ(. ^V e0( וsUkC]JdNE/B"ik(Ɗf_6]]2W|#FMIȂa!?HRhCmp!RG;fRN$(&RL*WV򕰌,gIZ̥.w^ 0ILLz %2IedZ.A%Fs1?mufCmnO^4NQ8Murg"1]R G&}l&B ̅2T1#Y E=ٷd A!лnf~3)&:R%H.Yh(ݧ8y29zXHzS I:ݒy״'9ES1)渶eu[6ǖIA5RMVIt+]%7:ΫrPVJ!.];=ۊԗZer-\7}骓 IeW]5V4SUMcmij}vIdcRTf kZ^5m{}e:rUA\ ik(dn@ =no(;F^.r0M$` cAAJpYꅯ|_l$kGYEV 28pCvdﵯ VF0`FnHnc1 -z7 /N=2Dˁf0|w t?+FEDIt.[֗$8r 0(U@:@s|Lg!Á̮Byx3L8)f+_b07p|7? U(drtil5+ BmNzѩF t-zՊ. J EaAF1w`{,`΂e?涺gYq53c}o~;Ƿ -Aڷ\.p?[F%N!fKpI<&gO9vT^򕻼0GesbMdMݴŭ-?ri.C.E-Ao:-uwҲĺuޥzQNhOpZ@;junit4-4.11/doc/cookstour/Image1.gif0000644000175000017500000000343412050524441016574 0ustar ebourgebourgGIF89a\,\@H*\ȰÇ#JHŋ3jȱǏ CI$H&S Dː,"f5sĉSAϝ12QDnL qAP&5*UUju׮`e#YN*0So8]q.+]t-CWzM,qŐFxLAWbya ~ q4ӨS^ͺװc˞MM֍7BkҜٓ8qDžLaGOdSޞݺS5Nӫ_~b|r |Vjf]wzcUa(g? GOU!}^^r!_r`h{0(h8<@)DtEdkK&bsH:TC9gB' b%:]fk eP>1\|5RfgzdT%gjh`1&AFk) hD>*^@*^U_i ^vږ\W*5]vUd'[zJ봓V/[fa;fjg-נfJEj+k,lK 7f* qGVx1gb1pQnHOM_OLi.K 5yh&lYcs8 %9L2+=͝QeU\]}X͗VUi_ s~MN:ob6pznoM]}o}hZ51{*ޅ*k-Qއ+8k(ު@2+( bVbGu.W妋Ny7KTۏ79tY_A?k 6^cϵ}F]}wDqi FS(Ëɞߴ$vctnNjS#A.9ˁ+!BH `H8̡w@H@;junit4-4.11/doc/cookstour/Image5.gif0000644000175000017500000001137212050524441016600 0ustar ebourgebourgGIF89a2,2@H*\ȰÇ#JHŋ3jȱǏ CIɓ(S\ɲ˗0cʜI͛8sɳD>c JѣHo]`iDIB@AUVb*`f Kvزhn5 YZ];jݵQ9`SMJ <K*ЮW!/dɔ/[Jgg<6iϛQk^}:t֬Mfo\  N|x]ȓԭ"УK>9ũt!СOӫ_Ͼ㗧N_9sݯWaw!w5PwF&Xᅈav!"X(zHb,>b0b4XG:R=*ȣaBIdHLP86H%V^颖3ee^~Pb^DfhyTWŵipŔJxCwBp%Z[rmYWɒpqFjDq7ގNyynwJy2Ȕ9ؗ)K}1V*무@+d)RYWX}"ZYnu,Eqb-т+~+Wv-rGgnm9/_tv ɟ:i?Z߿&pB'6 GHKg2oGY{ Ǭ)\1O@-DmH'L7PG-TWmu \7]_ܴd%mؒ]Mc]u[UMXyA|Fm[o8Vnef)ކo9;j_Kys .;q~oGp/K,ꦯ]춭}|qCk]؃܇|}O=~;}~'z=1GzYӊ pe*)c ۪s e~ϒmJIrIrW@#-5$HqP13]Nw, Q@1sʡwHX[4"惱I[gbU7d4z^h~ɢE j[HrUч%jD?w95nJx.SdF$!u*fce^ÚGڈdFG2/RHjAЀILSkĩDKzɴSbDu ʚ.R-*zԞ!g@תֶvj\Ň(ʫWկ}k`*X%bX•&Id+ɞY{EB́a %i֜X< Jf4-{#*n70|]n>qNb1oHJ(O'2 S%7y/ejyU›SX_c^3*T1zLq 5LʍX13V'&XwZT:gn&A:h~WG4<mrUf xGHArA 2ϦOm&ѽre UQ. Wņ1.V\BК7=#?ܪ&8iK1x]}otHP D]@M`a:#M`[ek6O8*p|י^酴!l}Ǚ?p1uM\/uiJ+I8˃[bG/Ϲma~Z$րo`AwXAk;B縇D#7T7]#"H]qk;f#l,uEYwd[cxn9GWɬ_l|5IShGOқOWֻgOϽweu!b:2vU\_q:gumM{k:Oߝ~qqE&1~XBV5{q*q2l}rlb,0(X}XׇPm#i{")6,G%h,.y%XSW(.XX^b{X$LrH!#U-JdI&mHgugKVsVCETM(CI!fmf=@\hSfnMHIhU7h7&SiXIk8g؅>BrvvxRRM$SBt8X*xn{|phhрGX9hX&hȇgcצ~(wa7N(xƘȌ5h&׈`ָӍ4ٸqaH3Ĥi4@F);v`W^"7rqr,Grڵt2G/CsBv_;bYPw['Vt@;ut!)s Ci-x\ yĒɇsw呫8b$qweP䤔OÔCc &RYezh 7_mij 7ۄc8^ v^z9!|UCb'5NYzE3ebf<%Y%9zy%9uId|LXƕSfo BUfn՚ qI׉gaCP "Q}cSUAbٗ٣wVril|Ne8JAU-fٕSG/f)?xB?#W؈(Qew蝹@ e0hiҟf@(%k#(Ƞ8yTY h6eh# %Aw7r@"Cgvz+ZP:(t1ZiM7ש]ȣ+iuyɡf f!zy urZoҏ:I49Tp˷Eg:4HwuJZ50kJxuK:9t6;{-sx 1jsag6=tjJ&ɺ1v7:7[VkSg;[KX[${u h=F*ktIv߫cM4m59yic+Gt%k[(G;鋿 c!aKʽ>(ZIW:zZ?fxKL x˕,nteZ׹)x" [v! qn[,|¹e[}kywE|{@\v,JlI<~JOZ&i*`F\f]Zވ k; 6F+VkfۨjR-J E{฿.DOP첺}/HT:|0H ;~r rV %Cp<Mʵq0,&NԲYyXk^_w&3lzEtc"ugf'jz֜֙5yu}N".ZY*jfzqHK3m#VWM\]W}kv٩G+)"3'wrJ9YjktoXyܼK%;nidMOzeFfGjjz=ۭz/o H^ YLsdر3rTґEE b$TTAn'I{ (]*W 78/qP0a 9H0 hۏzB谈1Dt5%O_;ĉL$W_KEuq[U(Fy0xZ~63ťcH!phx#8qyd)@B*"G R!E,򒐄4){yI5oq$ F~1FO 4R,JSڔ2+$7B J$hˤ5S DT]3= $ &9)(R5aӦٚiaK;i4ɞF 05><\<~~3f?M CyѳER&JУ写Kin43 C͓l)6ڣFIԢ:=RԦ:uq̀JXͪVգqJdϺJֲլ}hs#g\U~֣!xB=B Wv/wym4Rv]r[;㱊LYS_T_hYqgi DszNa@'RZS[ah*.ͭnY ҂NsmXl0V-55mtre%lc:XFw!o%r>7}-q8?=ۃ\pRԹU`5WM_y˳M0t+7{ GLZ;junit4-4.11/doc/cookstour/Image4.gif0000644000175000017500000000715612050524441016604 0ustar ebourgebourgGIF89a,@H*\ȰÇ#JHŋ3jȱǏ CIɓ(E"Hɒʖ0c|M6s9Ц@uSh˛2*tӠOJMtӪV&ŪU&׮`O~gO Ylƅ[-\aWl߿&}[Pr. EƎgF!v3Vʠ1zq4o\˚nWv}3IӨO-q7oʇ Nȓ \uX$H }uձS>=s~]uc'>|o\pkK|zy@ؠ 8{=!o-gb(b,_4&c8&X4GT!"z&=9VZ9Eݕ @.FYeEHQ7am"ݑ THbb Ng{g|I栂B)|*YC馜v駠*ꨤ(t5P?jawĥ{i5W뮼+찢;+1VDCױ;,ZDmsV;Qq-Dоljne.acy.KFf1kB%gEpiY&/(-S\qCY7ށeRL,CY˔{il؟>见Ik. 2j(](&э(A~zi0Gs[g.uc-vY \JͶU6r E*|7~Zƃ5b!'Rx^;q7+3H3Z84 Q+hLt+b> {}n{*ҬY+ƀ4V0][w 3G/Wog/U?,_k,b8*?[6ER ӟmVr$ ׺כfc*٥)*޹b.2@PX S~?!6dzx+( aZVbģ8i! wFiQ+L!A1 NUXƫq߳ƙbfVFb H5Bыȳ ^2 c%PTS\&dgZT串l"bN f/u[%&]Mu,ӆ UKM?Kʖb*4!yhi{iuNSB<'t'HOgLO A:։D;OlM>f:Ohs ysW_A/Iґg2C%Rt=0MZL[:ӗ4ũMsӝ4GdT*T?R]Yȥ 9Nm]T8;VժW#VzT3FM*19Ӭg,GUj f[KJWɕEϫISH5>O39m ,7ω.gšǚXr:rJk-28r +YlwVŭXoKzթ5$><_jAw7Uz,ͪvz xKMz^ ZVE}qY)߰ ׽e@IR14DtC&14p`S\ r!77ʴnf*8ʥN5j:5]Z֢Ng̲ xε98zIftb'^԰6[wej'rT{ޯ6 ]mf| dl `Y?wcK6r;-%JDK5x3X wvy2GW P9@Gι=+ZyKdՓџuHC,/ȋ,MƄ|.9yהTؓwT]x_(nw2E\iYʛ]B(Ϲ˪RΘ9z?Uҷ\yEwy|Dy#;De_'>b368Mh%v]|3LUcY?謉YűWP{ =y?O58E%nmhLx\"3)MM8Drryxbc#F9aefKUŠCv3ӨS^} Y˞z#lȣs}tߨ-N&㪅#_q9sУ-kb7],cn]矦W^׷)_{y׭O_u }iV\ w w`LV\b U!_RR`V!Z!U`#bT'/6(4h8<@)Di$O $J6L2٤QNieNVQV%mcfif\gIR \zeWjʄ&eI%li'~Z'S'N6ꨞWbBt* \@&Ijڪ VdZyj`j*I쯻1[ҚQ6e^:ezK-_j[jZroVluz,{&;yC 2> ?gCGM(SVWuR/[dmhlpqqm4(RxzS7F%NG&CG^my8ބƉ霑謓:{[c6{onGW.VCY3>=pav N~Oͷ@4|sP>MP@Iy GHYڵH0lBÈ V)m N"D%J`_HDbE ؕʉSC,6 f:˰-bYZ(ç]Y$@|gLUp Hr3-dio|W˺s*hstIt=~!רdiܙ΂/ʍq!(Ƥ}4$I-Rߢb"kh2R f K%򈋼#\%3"`,<st[!qStxGJ e#Y6FPᐓg1 J)k:ui6k?C:9=r(1s>ifc٩w-hJъZͨF7юz HGJҒ& JWR񩴥0-)R4w/Mw Қ@OԢnt3R+-#TǑBK^UY56[XUfcMhʠբiJo[\srsukRz½1KX&`el_*X6bVm%kA~l,IK?Ȟ=hMRvHl #z |[ք kFmY.\Aׁ]qGx]ݪVBw\VFr^ƼQ/Y սzdJ_<6\k>kEr PA/¡y  4X;1HTUA1ad] ĭ\@L"HNy7Q*Qґ 9e-ybXlMU~&5bVH:5gMϵ$fL3vΐLÆ QRh6عϓFfMPOT^9K7rVNzd575ć1|Ƶ^O4YY3Le:_oly{[j]H]YΘ >9I/THjU՚=opvRd6ݬpW.00[xi|zӀhO|ݥd ͎Lq ,O^xO6by3Zi{,De]I/ol\0GS{޸>A]gx?J?gz]zVc4wj+a\wB#t̨9=@<';|}jn}=۩jN{OGZA|7O^cǖ5E7nT5o{_>/ͪ9%^ͮxeKgCi%JoG?YUr3thO џZg_y3y[-=7JrD/:g~(wtk7KZgx(owo X|˧|ȁ'| X$x=~&؁+8,h|284X6x8:<؃>@B8DXFxH0Lxc6քPKTXcS^QZaO7[cd`E`e؃KiXm\\rX/!_lhEz؇*~\X^aޕb؈X%y5eemȉ艛U(dhiHcA f\́#a_!Յ 3`SRhWƈ8>X3Q?XxUWwh؎%(EXWaH > yht(Dc9hƑ(9XS `_+Y9\.2IT-)($yI69; A4 [GaE= PQoxV1Cؔ^`Od99Y*r5#lɒiIr9ab9sx1vz) kA[Xi]iu Qpi6ًYyb9c\ycH?YZ2J)m)`4ٙ_ ^Vٗ9Rُy~9x$51ɗ&q ҩW)ə5`9[Y\I i剞bY)i)^ɓX[@9ՙ JjI٩j a Jb YJʞʠ'JJ) !*#1aX/7 3 =z`ߩ=C*AڝJLڤNPR:TZVzXZ\ڥ^`ڝO/ e.ZB0j:k:fpڦiJxgPtʀ}&rq:wlgCwq~x!qӦC)f[nڨƤ:P@䩑:B*Qrjvǩw&1AfC0h*hb)TB L*wrA(5lsyؤ*Rdpj}{zgfʬ tJj ÚZ:I0"0vǭ{Jj111W/ u'rg/ʮRDs3~l]G)g;sb(C-+kZ_NRMy+ y kwF0ۧlZHgj:tBw|MG2G3iOP+1qm227'm+t-)8v˱o]dHFOo{;tlg3_gt}B~۵.1ktCF~;rv1Kf$[|rbm [۸po}a,[&Jlj;pu}{o_W$C~gf<˹wp[[vu'ku~K;xt K;g GpkSðKIz&Kokt컹ڹEѫ ̽zEeGmK},+J{ow9,E:'>B,yJFܰë-QsfMf<簥gX Z%q1$+Aw+(e*ÎjGPL@,Ċh|\mS CZUɣ*'gQdww!g6ʣFʫ71ǤToZі˲&ۂ 㶨 b Nȓ+_μУ-"aճk%uOzGАJo/ZW.ǸU\* FsIN'Ao$E4bUK5Uf̤ _`FGIweP/ Cq\ ;\91_GWWVbr7t̯ 2EhD6zэpcz&:Fk<񏀤BRt ! "EāV2'>IF+KqM &&Ld3 L#)VNV^n#2bcU0s!%44MTș6nz 8IrJ4:d4s`$I$==u;ZԠNA)\!Wc B;/T^cX.Q_ }?Fzʕ.sҕڒ#-) ӚhSaZ,s@ PJTڴ@Ȅ2PfK&@浗G%ȉլzUq]*ºM|g]ZggVouw\ JWEuv+^( `D1pM &֧tl"Z͢綃Z/W˜SNB\Оt\ ?10a(jjv8$̲U.S3\$t)DR(|Knƥ])πbH?h^z6=k_OgD['ٕ%H}-7T`d00Qyw9eigzJ׸ID(%JVmaFB"z0`gR5jE&3-16\Dn<gա -`ꦼ)*KXe.[>RLޡ+fA^&wmtT{iE~$t)q; A5xVOLa.3'tcS ʰ.Tr U8G'@;ȸRWI\6A>DgG)pDżoEVRj(yfkTeVJKm;ޅ-_z6&=`سI{pX3iTm2J]v* |߻oVnӒؤ-*]2 ,`8CRZ ׸3q)[,Y\[xM]Ο.ثЇkr_"h(Y>u1)C`GNŖr:nPsC܍]pGpm3^SH)<w=B5 ujV*bUj|= Ƴ{WE(x1L{hG-wOO4nn{1{kO A81:|I?L n_HJGEUDkG$s?Xzg>Bz.s0fb26pUs:Er(<\61}J^=t+!'BzXyBq5uRet(vH(waׄN+DXtVx!l&pZXv*zv]#zrcdR6b2q2SUmV~${h\ako&{\{fVcxk7b6NtX88 xY\刈vd(8g(||EP8*G؊䊸f5|E(vu勿8ShMh^}mا}co~F"\HfFRYRjxwuErH>ܷ3suZpGEj1TtKvfAv'X] "moeji>ŦJ1Q+VHI8ҕ\ʥJTwFiiz"Uǵ,dpP-D?ɖy)'z1Hq*qoX\WsL(kD`⧒5]׉'pI+QJu;5 /fIºh9>>9teȘ';t+&JM#gTUǹMMv5VgG{ŁQPJ`M[hjlnprICNF,H[哌9X'\晥Rp̪p> r> ~ zZwnt.n~߷nNyLP.Մ_.͖^rc:{ZmuJdk^njʕEy֯nE, C^訬ߜ.]-aWua.^{.B1^r>Bn&~yj.N='B)) XY]΢6j8d]SRڂel'oҘ{amBNyu;T_r*XM*:O>GP FE w=Bt)/{2؜>!?,fV x ߒdb^B\MW_(O3]z?mȟis榿4ٵ|ݘ.̺oH6M}>_ƿpd vGRAb|.Oh9@Ik˜d@H I@@ DPB "P@C-^(bF= d H$E<92ʕ*KTR̖"]e͚8}DPE 51Rj| ԦQ^u$˟!s 5fL $ tٵceU ؟m5h#D}'b#Ry,ܑo%PƇ-YV# 9mسm~+: Z{VM0hE̲mKVܛ 7$^49߀6,5_Ǟ}sKgi=t絨Ǘwgwޫ  J]υmKh9#@s? 4@-ʺ.DL`#-EpK\­4XoF n!>LjB r#,2B* (G38Sgc6R---M3Qt +1AT5,TP;PI#K2CG,),QLOB+TDROkTUQMUVMպ$Sc4)[CUW,,XwYeevYgFu5vQrZZV@6ܢ%YsE\8]3znAWbK"__&68aX>9sJ^+NZw+B~y矿 zj^9{76d~|8}g}O[''4ٶ|vFD(=+E_ȤVu? "ɫҵAuq'Y*x1O/kVrժ b:b!Nbݰ/!a<)f9#lV %mUf.w ;+Ұ. sXj'H$YK\!WF2ΰT\,aYdR8"vqrg0.2VZDR'7Dc8#ፎYb+2ٳ뜣yDqb"HTTpeOr'[e&i9Ζlc-iY:6-v{g2 UY)gL(jb `44Ac HlX p5i5QR8)Jәq AOZ4t*K CTժW*+Uvի_H Ք&F)XպVխ\XCW-[W.uU XnE yΰlaZC~lf5Eֳ'B'VTGXe *4he*ˌ%#>VMjK%еgmjUZ7%n?O1\-m[Ҷb.Ke䣬MdO:˶w;UD!K_޷hziREa sMԍmE95NpthƤ%IVR]׃ OҹTtQi=6K7gB=el,B6MLY2FLL,5m;%MP6Ӛ9ю|QgܧZe=;t@̞[=]ܨ72 x$Md3)ɑgRdM}㌬2́&AQUM:3CmuڸqEdZIdkTըJUXNySVF)PdXU鷋r{k\L?'GMbI4zz {bf2Nٚ_NS~{+uE>*Ӊ;Bz nA"E>r.Bvqw'RUrW+֗9o>tN(/Cv5O_z!&uSGzYw]zY,golѾvTm{vcRx~3|!._0!?y ~|Өyw^}-zҗ{G}Izַ>z}%{~ǽ=~?|?L'~5Eq7w~/Q_[_>ܭz[>kLj Wݗ_Oxmoqzu3f$Bs1 @jzO[ /谜1l@ Os@?2} |˴YKDcCE|6F L$9JĿNECbPDE++ULW JUnit Documentation

    JUnit Documentation

    Kent Beck, Erich Gamma, David Saff


    We have just begun documenting the new JUnit 4 architecture. The cookbook has already been updated. You can find the javadoc here. The JUnit home page is here.
    junit4-4.11/doc/ReleaseNotes4.8.2.txt0000644000175000017500000000004012050524441016464 0ustar ebourgebourgPlease see ReleaseNotes4.8.2.md junit4-4.11/doc/ReleaseNotes4.9.html0000644000175000017500000000661712050524441016472 0ustar ebourgebourg

    Summary of Changes in version 4.9, final

    Release theme: Test-class and suite level Rules.

    ClassRule

    The ClassRule annotation extends the idea of method-level Rules, adding static fields that can affect the operation of a whole class. Any subclass of ParentRunner, including the standard BlockJUnit4ClassRunner and Suite classes, will support ClassRules.

    For example, here is a test suite that connects to a server once before all the test classes run, and disconnects after they are finished:

    @RunWith(Suite.class)
    @SuiteClasses({A.class, B.class, C.class})
    public class UsesExternalResource {
        public static Server myServer= new Server();
    
        @ClassRule
        public static ExternalResource resource= new ExternalResource() {
            @Override
            protected void before() throws Throwable {
                myServer.connect();
            };
    
            @Override
            protected void after() {
                myServer.disconnect();
            };
        };
    }
    

    TestRule

    In JUnit 4.9, fields that can be annotated with either @Rule or @ClassRule should be of type TestRule. The old MethodRule type, which only made sense for method-level rules, will still work, but is deprecated.

    Most built-in Rules have been moved to the new type already, in a way that should be transparent to most users. TestWatchman has been deprecated, and replaced by TestWatcher, which has the same functionality, but implements the new type.

    Maven support

    Maven bundles have, in the past, been uploaded by kind volunteers. Starting with this release, the JUnit team is attempting to perform this task ourselves.

    LICENSE checked in

    The Common Public License that JUnit is released under is now included in the source repository.

    Bug fixes

    • github#98: assumeTrue() does not work with expected exceptions
    • github#74: Categories + Parameterized

      In JUnit 4.8.2, the Categories runner would fail to run correctly if any contained test class had a custom Runner with a structure significantly different from the built-in Runner. With this fix, such classes can be assigned one or more categories at the class level, and will be run correctly. Trying to assign categories to methods within such a class will flag an error.

    • github#38: ParentRunner filters more than once

      Thanks to @reinholdfuereder

    • github#248: protected BlockJUnit4ClassRunner#rules method removed from 4.8.2

    • github#187: Accidental dependency on Java 6

    Thanks to @kcooney for:

    • github#163: Bad comparison failure message when using assertEquals(String, String)
    • github#227: ParentRunner now assumes that getChildren() returns a modifiable list

    Minor changes

    • Backed out unused folder "experimental-use-of-antunit", replaced by bash-based script at build_tests.sh
    • Various Javadoc fixes

    Thanks to @kcooney for:

    • Made MultipleFailureException public, to assist extension writers.
    • github#240: Add "test" target to build.xml, for faster ant-driven testing.
    • github#247: Give InitializationError a useful message
    junit4-4.11/doc/ReleaseNotes4.9.txt0000644000175000017500000000003612050524441016332 0ustar ebourgebourgPlease see ReleaseNotes4.9.md junit4-4.11/doc/ReleaseNotes4.8.txt0000644000175000017500000000003612050524441016331 0ustar ebourgebourgPlease see ReleaseNotes4.8.md junit4-4.11/doc/ReleaseNotes4.7.html0000644000175000017500000001332112050524441016456 0ustar ebourgebourg

    Summary of Changes in version 4.7

    Rules

    • Rules allow very flexible addition or redefinition of the behavior of each test method in a test class. Testers can reuse or extend one of the provided Rules below, or write their own.

      For more on this feature, see http://www.threeriversinstitute.org/blog/?p=155

    • The TemporaryFolder Rule allows creation of files and folders that are guaranteed to be deleted when the test method finishes (whether it passes or fails):

      public static class HasTempFolder { @Rule public TemporaryFolder folder= new TemporaryFolder();

      @Test
      public void testUsingTempFolder() throws IOException {
          File createdFile= folder.newFile("myfile.txt");
          File createdFolder= folder.newFolder("subfolder");
          // ...
      }
      

      }

    • ExternalResource is a base class for Rules (like TemporaryFolder) that set up an external resource before a test (a file, socket, server, database connection, etc.), and guarantee to tear it down afterward:

      public static class UsesExternalResource { Server myServer = new Server();

      @Rule public ExternalResource resource = new ExternalResource() {
          @Override
          protected void before() throws Throwable {
              myServer.connect();
          };
      
      
      
      @Override
      protected void after() {
          myServer.disconnect();
      };
      
      }; @Test public void testFoo() { new Client().run(myServer); }

      }

    • The ErrorCollector Rule allows execution of a test to continue after the first problem is found (for example, to collect all the incorrect rows in a table, and report them all at once):

      public static class UsesErrorCollectorTwice { @Rule public ErrorCollector collector= new ErrorCollector();

      @Test public void example() {
          collector.addError(new Throwable("first thing went wrong"));
          collector.addError(new Throwable("second thing went wrong"));
      }
      

      }

    • Verifier is a base class for Rules like ErrorCollector, which can turn otherwise passing test methods into failing tests if a verification check is failed

      public static class ErrorLogVerifier() { private ErrorLog errorLog = new ErrorLog();

      @Rule public MethodRule verifier = new Verifier() { @Override public void verify() { assertTrue(errorLog.isEmpty()); } }

      @Test public void testThatMightWriteErrorLog() { // ... } }

    • TestWatchman is a base class for Rules that take note of the testing action, without modifying it. For example, this class will keep a log of each passing and failing test:

      public static class WatchmanTest { private static String watchedLog;

      @Rule
      public MethodRule watchman= new TestWatchman() {
          @Override
          public void failed(Throwable e, FrameworkMethod method) {
              watchedLog+= method.getName() + " "
                      + e.getClass().getSimpleName() + "\n";
          }
      
      
      
      @Override
      public void succeeded(FrameworkMethod method) {
          watchedLog+= method.getName() + " " + "success!\n";
      }
      
      }; @Test public void fails() { fail(); } @Test public void succeeds() { }

      }

    • The TestName Rule makes the current test name available inside test methods:

      public class NameRuleTest { @Rule public TestName name = new TestName();

      @Test public void testA() {
          assertEquals("testA", name.getMethodName());
      }
      
      
      @Test public void testB() {
          assertEquals("testB", name.getMethodName());
      }
      

      }

    • The Timeout Rule applies the same timeout to all test methods in a class:

      public static class HasGlobalTimeout { public static String log;

      @Rule public MethodRule globalTimeout = new Timeout(20);
      
      
      @Test public void testInfiniteLoop1() {
          log+= "ran1";
          for(;;) {}
      }
      
      
      @Test public void testInfiniteLoop2() {
          log+= "ran2";
          for(;;) {}
      }
      

      }

    • The ExpectedException Rule allows in-test specification of expected exception types and messages:

      public static class HasExpectedException { @Rule public ExpectedException thrown= ExpectedException.none();

      @Test
      public void throwsNothing() {
      
      
      }
      
      
      @Test
      public void throwsNullPointerException() {
          thrown.expect(NullPointerException.class);
          throw new NullPointerException();
      }
      
      
      @Test
      public void throwsNullPointerExceptionWithMessage() {
          thrown.expect(NullPointerException.class);
          thrown.expectMessage("happened?");
          thrown.expectMessage(startsWith("What"));
          throw new NullPointerException("What happened?");
      }
      

      }

    Timeouts

    • Tests that time out now show the stack trace of the test thread.

    Matchers

    • Due to typing incompatibilities, JUnit is still including the 1.1 release of hamcrest. This is not a change from 4.6, but is a change from pre-beta releases of 4.7. Due to this incompatibility, tests using Hamcrest 1.2 must still use the MatcherAssert.assertThat method from Hamcrest, not Assert.assertThat from JUnit.

    Docs

    • Javadocs now link to online JDK javadocs (bug 2090230)
    • Parameterized runner javadocs improved (bug 2186792)
    • Fixed Javadoc code sample for AfterClass (2126279)
    • Fixed Javadoc for assertArraysEqual(float[], float[])

    Bug fixes

    • Fixed: BaseTestRunner.getTest() requires class to extend TestCase (1812200)
    • Fixed: Suite does not allow for inheritance in annotations (2783118)
    • Fixed: ParallelComputer skipped tests that took longer than 2 seconds
    junit4-4.11/doc/ReleaseNotes4.9.md0000644000175000017500000000572512050524441016125 0ustar ebourgebourg## Summary of Changes in version 4.9, final ## Release theme: Test-class and suite level Rules. ### ClassRule ### The `ClassRule` annotation extends the idea of method-level Rules, adding static fields that can affect the operation of a whole class. Any subclass of `ParentRunner`, including the standard `BlockJUnit4ClassRunner` and `Suite` classes, will support `ClassRule`s. For example, here is a test suite that connects to a server once before all the test classes run, and disconnects after they are finished: @RunWith(Suite.class) @SuiteClasses({A.class, B.class, C.class}) public class UsesExternalResource { public static Server myServer= new Server(); @ClassRule public static ExternalResource resource= new ExternalResource() { @Override protected void before() throws Throwable { myServer.connect(); }; @Override protected void after() { myServer.disconnect(); }; }; } ### TestRule ### In JUnit 4.9, fields that can be annotated with either `@Rule` or `@ClassRule` should be of type `TestRule`. The old `MethodRule` type, which only made sense for method-level rules, will still work, but is deprecated. Most built-in Rules have been moved to the new type already, in a way that should be transparent to most users. `TestWatchman` has been deprecated, and replaced by `TestWatcher`, which has the same functionality, but implements the new type. ### Maven support ### Maven bundles have, in the past, been uploaded by kind volunteers. Starting with this release, the JUnit team is attempting to perform this task ourselves. ### LICENSE checked in ### The Common Public License that JUnit is released under is now included in the source repository. ### Bug fixes ### - github#98: assumeTrue() does not work with expected exceptions - github#74: Categories + Parameterized In JUnit 4.8.2, the Categories runner would fail to run correctly if any contained test class had a custom Runner with a structure significantly different from the built-in Runner. With this fix, such classes can be assigned one or more categories at the class level, and will be run correctly. Trying to assign categories to methods within such a class will flag an error. - github#38: ParentRunner filters more than once Thanks to `@reinholdfuereder` - github#248: protected BlockJUnit4ClassRunner#rules method removed from 4.8.2 - github#187: Accidental dependency on Java 6 Thanks to `@kcooney` for: - github#163: Bad comparison failure message when using assertEquals(String, String) - github#227: ParentRunner now assumes that getChildren() returns a modifiable list ### Minor changes ### - Backed out unused folder "experimental-use-of-antunit", replaced by bash-based script at build_tests.sh - Various Javadoc fixes Thanks to `@kcooney` for: - Made MultipleFailureException public, to assist extension writers. - github#240: Add "test" target to build.xml, for faster ant-driven testing. - github#247: Give InitializationError a useful message junit4-4.11/doc/ReleaseNotes4.8.md0000644000175000017500000000261012050524441016112 0ustar ebourgebourg## Summary of Changes in version 4.8 ## ### Categories ### From a given set of test classes, the `Categories` runner runs only the classes and methods that are annotated with either the category given with the `@IncludeCategory` annotation, or a subtype of that category. Either classes or interfaces can be used as categories. Subtyping works, so if you say `@IncludeCategory(SuperClass.class)`, a test marked `@Category({SubClass.class})` will be run. You can also exclude categories by using the `@ExcludeCategory` annotation Example: public interface FastTests { /* category marker */ } public interface SlowTests { /* category marker */ } public class A { @Test public void a() { fail(); } @Category(SlowTests.class) @Test public void b() { } } @Category({SlowTests.class, FastTests.class}) public class B { @Test public void c() { } } @RunWith(Categories.class) @IncludeCategory(SlowTests.class) @SuiteClasses( { A.class, B.class }) // Note that Categories is a kind of Suite public class SlowTestSuite { // Will run A.b and B.c, but not A.a } @RunWith(Categories.class) @IncludeCategory(SlowTests.class) @ExcludeCategory(FastTests.class) @SuiteClasses( { A.class, B.class }) // Note that Categories is a kind of Suite public class SlowTestSuite { // Will run A.b, but not A.a or B.c } ### Bug fixes ### - github#16: thread safety of Result countingjunit4-4.11/doc/ReleaseNotes4.6.md0000644000175000017500000000574112050524441016120 0ustar ebourgebourg## Summary of Changes in version 4.6 ## ### Max ### JUnit now includes a new experimental Core, `MaxCore`. `MaxCore` remembers the results of previous test runs in order to run new tests out of order. `MaxCore` prefers new tests to old tests, fast tests to slow tests, and recently failing tests to tests that last failed long ago. There's currently not a standard UI for running `MaxCore` included in JUnit, but there is a UI included in the JUnit Max Eclipse plug-in at: http://www.junitmax.com/junitmax/subscribe.html Example: public static class TwoUnEqualTests { @Test public void slow() throws InterruptedException { Thread.sleep(100); fail(); } @Test public void fast() { fail(); } } @Test public void rememberOldRuns() { File maxFile = new File("history.max"); MaxCore firstMax = MaxCore.storedLocally(maxFile); firstMax.run(TwoUnEqualTests.class); MaxCore useHistory= MaxCore.storedLocally(maxFile); List failures= useHistory.run(TwoUnEqualTests.class) .getFailures(); assertEquals("fast", failures.get(0).getDescription().getMethodName()); assertEquals("slow", failures.get(1).getDescription().getMethodName()); } ### Test scheduling strategies ### `JUnitCore` now includes an experimental method that allows you to specify a model of the `Computer` that runs your tests. Currently, the only built-in Computers are the default, serial runner, and two runners provided in the `ParallelRunner` class: `ParallelRunner.classes()`, which runs classes in parallel, and `ParallelRunner.methods()`, which runs classes and methods in parallel. This feature is currently less stable than MaxCore, and may be merged with MaxCore in some way in the future. Example: public static class Example { @Test public void one() throws InterruptedException { Thread.sleep(1000); } @Test public void two() throws InterruptedException { Thread.sleep(1000); } } @Test public void testsRunInParallel() { long start= System.currentTimeMillis(); Result result= JUnitCore.runClasses(ParallelComputer.methods(), Example.class); assertTrue(result.wasSuccessful()); long end= System.currentTimeMillis(); assertThat(end - start, betweenInclusive(1000, 1500)); } ### Comparing double arrays ### Arrays of doubles can be compared, using a delta allowance for equality: @Test public void doubleArraysAreEqual() { assertArrayEquals(new double[] {1.0, 2.0}, new double[] {1.0, 2.0}, 0.01); } ### `Filter.matchDescription` API ### Since 4.0, it has been possible to run a single method using the `Request.method` API. In 4.6, the filter that implements this is exposed as `Filter.matchDescription`. ### Documentation ### - A couple classes and packages that once had empty javadoc have been doc'ed. - Added how to run JUnit from the command line to the cookbook. - junit-4.x.zip now contains build.xml ### Bug fixes ### - Fixed overly permissive @DataPoint processing (2191102) - Fixed bug in test counting after an ignored method (2106324) junit4-4.11/doc/ReleaseNotes4.5.txt0000644000175000017500000000003612050524441016326 0ustar ebourgebourgPlease see ReleaseNotes4.5.md junit4-4.11/doc/ReleaseNotes4.10.txt0000644000175000017500000000003712050524441016403 0ustar ebourgebourgPlease see ReleaseNotes4.10.md junit4-4.11/doc/ReleaseNotes4.4.txt0000644000175000017500000000003612050524441016325 0ustar ebourgebourgPlease see ReleaseNotes4.4.md junit4-4.11/doc/ReleaseNotes4.8.1.md0000644000175000017500000000026212050524441016252 0ustar ebourgebourg## Summary of Changes in version 4.8.1 ## This was a quick bugfix release for an important bug ### Bug fixes ### - github#61: Category annotations on classes were not honored.junit4-4.11/doc/ReleaseNotes4.8.1.html0000644000175000017500000000032012050524441016611 0ustar ebourgebourg

    Summary of Changes in version 4.8.1

    This was a quick bugfix release for an important bug

    Bug fixes

    • github#61: Category annotations on classes were not honored.
    junit4-4.11/doc/ReleaseNotes4.7.txt0000644000175000017500000000003612050524441016330 0ustar ebourgebourgPlease see ReleaseNotes4.7.md junit4-4.11/doc/ReleaseNotes4.11.txt0000644000175000017500000000003712050524441016404 0ustar ebourgebourgPlease see ReleaseNotes4.11.md junit4-4.11/doc/building-junit.txt0000644000175000017500000000105312050524441016432 0ustar ebourgebourgSteps to build junit: - Must be manual - Write release notes - Update version in build.xml - Not too tedious: - Push to github (dsaff _and_ KentBeck) - Run the ant zip task - Upload stuff to github (including tag) - Push to maven - ant -lib build/lib stage.maven - Promote - Tedious: - Update SourceForge if major release - Update javadocs on github site (and "latest" link) - Update javadocs on junit.org - Put release notes on github. - Announce on blog, user list, dev list, announce list, junit.org, twitter - Profit! junit4-4.11/doc/ReleaseNotes4.11.md0000644000175000017500000001142312050524441016166 0ustar ebourgebourg## Summary of changes in version 4.11 ### Matchers: Upgrade to Hamcrest 1.3 JUnit now uses the latest version of Hamcrest. Thus, you can use all the available matchers and benefit from an improved `assertThat` which will now print the mismatch description from the matcher when an assertion fails. #### Example assertThat(Long.valueOf(1), instanceOf(Integer.class)); Old error message: Expected: an instance of java.lang.Integer got: <1L> New error message: Expected: an instance of java.lang.Integer but: <1L> is a java.lang.Long Hamcrest's new `FeatureMatcher` makes writing custom matchers that make use of custom mismatch descriptions quite easy: @Test public void featureMatcher() throws Exception { assertThat("Hello World!", length(is(0))); } private Matcher length(Matcher matcher) { return new FeatureMatcher(matcher, "a String of length that", "length") { @Override protected Integer featureValueOf(String actual) { return actual.length(); } }; } Running this test will return the following failure message: Expected: a String of length that is <0> but: length was <12> Most of the matchers in `JUnitMatchers` have been deprecated. Please use `org.hamcrest.CoreMatchers` directly. ### Parameterized Tests In order to easily identify the individual test cases in a Parameterized test, you may provide a name using the `@Parameters` annotation. This name is allowed to contain placeholders that are replaced at runtime: * `{index}`: the current parameter index * `{0}`, `{1}`, …: the first, second, and so on, parameter value #### Example @RunWith(Parameterized.class) public class FibonacciTest { @Parameters(name = "{index}: fib({0})={1}") public static Iterable data() { return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } }); } private int input; private int expected; public FibonacciTest(int input, int expected) { this.input = input; this.expected = expected; } @Test public void test() { assertEquals(expected, Fibonacci.compute(input)); } } In the example given above, the `Parameterized` runner creates names like `[1: fib(3)=2]`. If you don't specify a name, the current parameter index will be used by default. ### Test execution order By design, JUnit does not specify the execution order of test method invocations. Until now, the methods were simply invoked in the order returned by the reflection API. However, using the JVM order is unwise since the Java platform does not specify any particular order, and in fact JDK 7 returns a more or less random order. Of course, well-written test code would not assume any order, but some does, and a predictable failure is better than a random failure on certain platforms. From now on, JUnit will by default use a deterministic, but not predictable, order (`MethodSorters.DEFAULT`). To change the test execution order simply annotate your test class using `@FixMethodOrder` and specify one of the available `MethodSorters`: * `@FixMethodOrder(MethodSorters.JVM)`: Leaves the test methods in the order returned by the JVM. This order may vary from run to run. * `@FixMethodOrder(MethodSorters.NAME_ASCENDING)`: Sorts the test methods by method name, in lexicographic order. ### Maven artifacts Up until now there were two Maven artifacts for JUnit: `junit:junit-dep` and `junit:junit`. From a Maven point-of-view only the former made sense because it did not contain the Hamcrest classes but declared a dependency to the Hamcrest Maven artifact. The latter included the Hamcrest classes which was very un-Maven-like. From this release on, you should use `junit:junit` which will be what `junit:junit-dep` used to. If you still reference `junit:junit-dep`, Maven will automatically relocate you to the new `junit:junit` and issue a warning for you to fix. ### Rules A number of improvements have been made to Rules: * `MethodRule` is no longer deprecated. * Both `@Rule` and `@ClassRule` can now be used on methods that return a `TestRule`. * `ExpectedException` now always prints the stacktrace of the actual exception in case of failure. * A parent folder can be specified for `TemporaryFolder`. In addition, the `newFile`/`newFolder` methods will now fail when the file or folder could not be created. * `TestWatcher` has a new template method called `skipped` that is invoked when a test is skipped due to a failed assumption. ### Improvements to Assert and Assume * `assertNotEquals` has been added to `Assert`. * `assertEquals` has been overloaded in order to check whether two floats are equal given a certain float delta. * Most methods in `Assume` now allow to pass a custom message. junit4-4.11/doc/ReleaseNotes4.4.md0000644000175000017500000002673012050524441016117 0ustar ebourgebourg## Summary of Changes in version 4.5 ## ### Categories ### Each test method and test class can be annotated as belonging to a _category_: public static class SomeUITests { @Category(UserAvailable.class) @Test public void askUserToPressAKey() { } @Test public void simulatePressingKey() { } } @Category(InternetConnected.class) public static class InternetTests { @Test public void pingServer() { } } To run all of the tests in a particular category, you must currently explicitly create a custom request: new JUnitCore().run(Request.aClass(SomeUITests.class).inCategories(UserAvailable.class)); This feature will very likely be improved before the final release of JUnit 4.5 ### Theories ### - `@Before` and `@After` methods are run before and after each set of attempted parameters on a Theory, and each set of parameters is run on a new instance of the test class. - Exposed API's `ParameterSignature.getType()` and `ParameterSignature.getAnnotations()` - An array of data points can be introduced by a field or method marked with the new annotation `@DataPoints` - The Theories custom runner has been refactored to make it easier to extend ### JUnit 4 Runner API ### - There has been a drastic rewrite of the API for custom Runners in 4.5. This needs to be written up separately before release. - Tests with failed assumptions are now marked as Ignored, rather than silently passing. This may change behavior in some client tests, and also will require some new support on the part of IDE's. ## Summary of Changes in version 4.4 ## JUnit is designed to efficiently capture developers' intentions about their code, and quickly check their code matches those intentions. Over the last year, we've been talking about what things developers would like to say about their code that have been difficult in the past, and how we can make them easier. [Download][] [Download]: http://sourceforge.net/project/showfiles.php?group_id=15278 ### assertThat ### Two years ago, Joe Walnes built a [new assertion mechanism][walnes] on top of what was then [JMock 1][]. The method name was `assertThat`, and the syntax looked like this: [walnes]: http://joe.truemesh.com/blog/000511.html [JMock 1]: http://www.jmock.org/download.html assertThat(x, is(3)); assertThat(x, is(not(4))); assertThat(responseString, either(containsString("color")).or(containsString("colour"))); assertThat(myList, hasItem("3")); More generally: assertThat([value], [matcher statement]); Advantages of this assertion syntax include: - More readable and typeable: this syntax allows you to think in terms of subject, verb, object (assert "x is 3") rather than `assertEquals`, which uses verb, object, subject (assert "equals 3 x") - Combinations: any matcher statement `s` can be negated (`not(s)`), combined (`either(s).or(t)`), mapped to a collection (`each(s)`), or used in custom combinations (`afterFiveSeconds(s)`) - Readable failure messages. Compare assertTrue(responseString.contains("color") || responseString.contains("colour")); // ==> failure message: // java.lang.AssertionError: assertThat(responseString, anyOf(containsString("color"), containsString("colour"))); // ==> failure message: // java.lang.AssertionError: // Expected: (a string containing "color" or a string containing "colour") // got: "Please choose a font" - Custom Matchers. By implementing the `Matcher` interface yourself, you can get all of the above benefits for your own custom assertions. - For a more thorough description of these points, see [Joe Walnes's original post][walnes]. We have decided to include this API directly in JUnit. It's an extensible and readable syntax, and it enables new features, like [assumptions][] and [theories][]. [assumptions]: #assumptions [theories]: #theories Some notes: - The old assert methods are never, ever, going away. Developers may continue using the old `assertEquals`, `assertTrue`, and so on. - The second parameter of an `assertThat` statement is a `Matcher`. We include the Matchers we want as static imports, like this: import static org.hamcrest.CoreMatchers.is; or: import static org.hamcrest.CoreMatchers.*; - Manually importing `Matcher` methods can be frustrating. [Eclipse 3.3][] includes the ability to define "Favorite" classes to import static methods from, which makes it easier (Search for "Favorites" in the Preferences dialog). We expect that support for static imports will improve in all Java IDEs in the future. [Eclipse 3.3]: http://www.eclipse.org/downloads/ - To allow compatibility with a wide variety of possible matchers, we have decided to include the classes from hamcrest-core, from the [Hamcrest][] project. This is the first time that third-party classes have been included in JUnit. [Hamcrest]: http://code.google.com/p/hamcrest/ - JUnit currently ships with a few matchers, defined in `org.hamcrest.CoreMatchers` and `org.junit.matchers.JUnitMatchers`. To use many, many more, consider downloading the [full hamcrest package][]. [full hamcrest package]: http://hamcrest.googlecode.com/files/hamcrest-all-1.1.jar - JUnit contains special support for comparing string and array values, giving specific information on how they differ. This is not yet available using the `assertThat` syntax, but we hope to bring the two assert methods into closer alignment in future releases. ### Assumptions ### Ideally, the developer writing a test has control of all of the forces that might cause a test to fail. If this isn't immediately possible, making dependencies explicit can often improve a design. For example, if a test fails when run in a different locale than the developer intended, it can be fixed by explicitly passing a locale to the domain code. However, sometimes this is not desirable or possible. It's good to be able to run a test against the code as it is currently written, implicit assumptions and all, or to write a test that exposes a known bug. For these situations, JUnit now includes the ability to express "assumptions": import static org.junit.Assume.* @Test public void filenameIncludesUsername() { assumeThat(File.separatorChar, is('/')); assertThat(new User("optimus").configFileName(), is("configfiles/optimus.cfg")); } @Test public void correctBehaviorWhenFilenameIsNull() { assumeTrue(bugFixed("13356")); // bugFixed is not included in JUnit assertThat(parse(null), is(new NullDocument())); } With this release, a failed assumption will lead to the test being marked as passing, regardless of what the code below the assumption may assert. In the future, this may change, and a failed assumption may lead to the test being ignored: however, third-party runners do not currently allow this option. We have included `assumeTrue` for convenience, but thanks to the inclusion of Hamcrest, we do not need to create `assumeEquals`, `assumeSame`, and other analogues to the `assert*` methods. All of those functionalities are subsumed in `assumeThat`, with the appropriate matcher. A failing assumption in a `@Before` or `@BeforeClass` method will have the same effect as a failing assumption in each `@Test` method of the class. ### Theories ### More flexible and expressive assertions, combined with the ability to state assumptions clearly, lead to a new kind of statement of intent, which we call a "Theory". A test captures the intended behavior in one particular scenario. A theory captures some aspect of the intended behavior in possibly infinite numbers of potential scenarios. For example: @RunWith(Theories.class) public class UserTest { @DataPoint public static String GOOD_USERNAME = "optimus"; @DataPoint public static String USERNAME_WITH_SLASH = "optimus/prime"; @Theory public void filenameIncludesUsername(String username) { assumeThat(username, not(containsString("/"))); assertThat(new User(username).configFileName(), containsString(username)); } } This makes it clear that the user's filename should be included in the config file name, only if it doesn't contain a slash. Another test or theory might define what happens when a username does contain a slash. `UserTest` will attempt to run `filenameIncludesUsername` on every compatible `DataPoint` defined in the class. If any of the assumptions fail, the data point is silently ignored. If all of the assumptions pass, but an assertion fails, the test fails. The support for Theories has been absorbed from the [Popper][] project, and [more complete documentation][popper-docs] can be found there. [Popper]: http://popper.tigris.org [popper-docs]: http://popper.tigris.org/tutorial.html Defining general statements in this way can jog the developer's memory about other potential data points and tests, also allows [automated tools][junit-factory] to [search][my-blog] for new, unexpected data points that expose bugs. [junit-factory]: http://www.junitfactory.org [my-blog]: http://shareandenjoy.saff.net/2007/04/popper-and-junitfactory.html ### Other changes ### This release contains other bug fixes and new features. Among them: - Annotated descriptions Runner UIs, Filters, and Sorters operate on Descriptions of test methods and test classes. These Descriptions now include the annotations on the original Java source element, allowing for richer display of test results, and easier development of annotation-based filters. - Bug fix (1715326): assertEquals now compares all Numbers using their native implementation of `equals`. This assertion, which passed in 4.3, will now fail: assertEquals(new Integer(1), new Long(1)); Non-integer Numbers (Floats, Doubles, BigDecimals, etc), which were compared incorrectly in 4.3, are now fixed. - `assertEquals(long, long)` and `assertEquals(double, double)` have been re-introduced to the `Assert` class, to take advantage of Java's native widening conversions. Therefore, this still passes: assertEquals(1, 1L); - The default runner for JUnit 4 test classes has been refactored. The old version was named `TestClassRunner`, and the new is named `JUnit4ClassRunner`. Likewise, `OldTestClassRunner` is now `JUnit3ClassRunner`. The new design allows variations in running individual test classes to be expressed with fewer custom classes. For a good example, see the source to `org.junit.experimental.theories.Theories`. - The rules for determining which runner is applied by default to a test class have been simplified: 1. If the class has a `@RunWith` annotation, the annotated runner class is used. 2. If the class can be run with the JUnit 3 test runner (it subclasses `TestCase`, or contains a `public static Test suite()` method), JUnit38ClassRunner is used. 3. Otherwise, JUnit4ClassRunner is used. This default guess can always be overridden by an explicit `@RunWith(JUnit4ClassRunner.class)` or `@RunWith(JUnit38ClassRunner.class)` annotation. The old class names `TestClassRunner` and `OldTestClassRunner` remain as deprecated. - Bug fix (1739095): Filters and Sorters work correctly on test classes that contain a `suite` method like: public static junit.framework.Test suite() { return new JUnit4TestAdapter(MyTest.class); } - Bug fix (1745048): @After methods are now correctly called after a test method times out. junit4-4.11/doc/ReleaseNotes4.11.html0000644000175000017500000001312212050524441016530 0ustar ebourgebourg

    Summary of changes in version 4.11

    Matchers: Upgrade to Hamcrest 1.3

    JUnit now uses the latest version of Hamcrest. Thus, you can use all the available matchers and benefit from an improved assertThat which will now print the mismatch description from the matcher when an assertion fails.

    Example

    assertThat(Long.valueOf(1), instanceOf(Integer.class));
    

    Old error message:

    Expected: an instance of java.lang.Integer
         got: <1L>
    

    New error message:

    Expected: an instance of java.lang.Integer
         but: <1L> is a java.lang.Long
    

    Hamcrest's new FeatureMatcher makes writing custom matchers that make use of custom mismatch descriptions quite easy:

    @Test
    public void featureMatcher() throws Exception {
        assertThat("Hello World!", length(is(0)));
    }
    
    private Matcher<String> length(Matcher<? super Integer> matcher) {
        return new FeatureMatcher<String, Integer>(matcher, "a String of length that", "length") {
            @Override
            protected Integer featureValueOf(String actual) {
                return actual.length();
            }
        };
    }
    

    Running this test will return the following failure message:

    Expected: a String of length that is <0>
         but: length was <12>
    

    Most of the matchers in JUnitMatchers have been deprecated. Please use org.hamcrest.CoreMatchers directly.

    Parameterized Tests

    In order to easily identify the individual test cases in a Parameterized test, you may provide a name using the @Parameters annotation. This name is allowed to contain placeholders that are replaced at runtime:

    • {index}: the current parameter index
    • {0}, {1}, …: the first, second, and so on, parameter value

    Example

    @RunWith(Parameterized.class)
    public class FibonacciTest {
    
        @Parameters(name = "{index}: fib({0})={1}")
        public static Iterable<Object[]> data() {
            return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 },
                    { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } });
        }
    
        private int input;
        private int expected;
    
        public FibonacciTest(int input, int expected) {
            this.input = input;
            this.expected = expected;
        }
    
        @Test
        public void test() {
            assertEquals(expected, Fibonacci.compute(input));
        }
    }
    

    In the example given above, the Parameterized runner creates names like [1: fib(3)=2]. If you don't specify a name, the current parameter index will be used by default.

    Test execution order

    By design, JUnit does not specify the execution order of test method invocations. Until now, the methods were simply invoked in the order returned by the reflection API. However, using the JVM order is unwise since the Java platform does not specify any particular order, and in fact JDK 7 returns a more or less random order. Of course, well-written test code would not assume any order, but some does, and a predictable failure is better than a random failure on certain platforms.

    From now on, JUnit will by default use a deterministic, but not predictable, order (MethodSorters.DEFAULT). To change the test execution order simply annotate your test class using @FixMethodOrder and specify one of the available MethodSorters:

    • @FixMethodOrder(MethodSorters.JVM): Leaves the test methods in the order returned by the JVM. This order may vary from run to run.

    • @FixMethodOrder(MethodSorters.NAME_ASCENDING): Sorts the test methods by method name, in lexicographic order.

    Maven artifacts

    Up until now there were two Maven artifacts for JUnit: junit:junit-dep and junit:junit. From a Maven point-of-view only the former made sense because it did not contain the Hamcrest classes but declared a dependency to the Hamcrest Maven artifact. The latter included the Hamcrest classes which was very un-Maven-like.

    From this release on, you should use junit:junit which will be what junit:junit-dep used to. If you still reference junit:junit-dep, Maven will automatically relocate you to the new junit:junit and issue a warning for you to fix.

    Rules

    A number of improvements have been made to Rules:

    • MethodRule is no longer deprecated.
    • Both @Rule and @ClassRule can now be used on methods that return a TestRule.
    • ExpectedException now always prints the stacktrace of the actual exception in case of failure.
    • A parent folder can be specified for TemporaryFolder. In addition, the newFile/newFolder methods will now fail when the file or folder could not be created.
    • TestWatcher has a new template method called skipped that is invoked when a test is skipped due to a failed assumption.

    Improvements to Assert and Assume

    • assertNotEquals has been added to Assert.
    • assertEquals has been overloaded in order to check whether two floats are equal given a certain float delta.
    • Most methods in Assume now allow to pass a custom message.
    junit4-4.11/LICENSE0000644000175000017500000002662212050524441013216 0ustar ebourgebourgJUnit Common Public License - v 1.0 THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS COMMON PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 1. DEFINITIONS "Contribution" means: a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and b) in the case of each subsequent Contributor: i) changes to the Program, and ii) additions to the Program; where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program. "Contributor" means any person or entity that distributes the Program. "Licensed Patents " mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. "Program" means the Contributions distributed in accordance with this Agreement. "Recipient" means anyone who receives the Program under this Agreement, including all Contributors. 2. GRANT OF RIGHTS a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form. b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. 3. REQUIREMENTS A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that: a) it complies with the terms and conditions of this Agreement; and b) its license agreement: i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange. When the Program is made available in source code form: a) it must be made available under this Agreement; and b) a copy of this Agreement must be included with each copy of the Program. Contributors may not remove or alter any copyright notices contained within the Program. Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution. 4. COMMERCIAL DISTRIBUTION Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. 5. NO WARRANTY EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement, including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. 6. DISCLAIMER OF LIABILITY EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 7. GENERAL If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. If Recipient institutes patent litigation against a Contributor with respect to a patent applicable to software (including a cross-claim or counterclaim in a lawsuit), then any patent licenses granted by that Contributor to such Recipient under this Agreement shall terminate as of the date such litigation is filed. In addition, if Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. IBM is the initial Agreement Steward. IBM may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation. junit4-4.11/.project0000644000175000017500000000064312050524441013653 0ustar ebourgebourg junit org.eclipse.jdt.core.javabuilder org.eclipse.jdt.core.javanature org.eclipse.team.cvs.core.cvsnature junit4-4.11/src/0000755000175000017500000000000012050524441012770 5ustar ebourgebourgjunit4-4.11/src/test/0000755000175000017500000000000012050524441013747 5ustar ebourgebourgjunit4-4.11/src/test/java/0000755000175000017500000000000012050524441014670 5ustar ebourgebourgjunit4-4.11/src/test/java/junit/0000755000175000017500000000000012050524441016021 5ustar ebourgebourgjunit4-4.11/src/test/java/junit/tests/0000755000175000017500000000000012050524441017163 5ustar ebourgebourgjunit4-4.11/src/test/java/junit/tests/package-info.java0000644000175000017500000000007712050524441022356 0ustar ebourgebourg/** * Tests the JUnit v3.x framework. */ package junit.tests;junit4-4.11/src/test/java/junit/tests/extensions/0000755000175000017500000000000012050524441021362 5ustar ebourgebourgjunit4-4.11/src/test/java/junit/tests/extensions/package-info.java0000644000175000017500000000013412050524441024547 0ustar ebourgebourg/** * Tests for the JUnit v3.x extension functionality. */ package junit.tests.extensions;junit4-4.11/src/test/java/junit/tests/extensions/RepeatedTestTest.java0000644000175000017500000000326312050524441025462 0ustar ebourgebourgpackage junit.tests.extensions; import junit.extensions.RepeatedTest; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestResult; import junit.framework.TestSuite; /** * Testing the RepeatedTest support. */ public class RepeatedTestTest extends TestCase { private TestSuite fSuite; public static class SuccessTest extends TestCase { @Override public void runTest() { } } public RepeatedTestTest(String name) { super(name); fSuite = new TestSuite(); fSuite.addTest(new SuccessTest()); fSuite.addTest(new SuccessTest()); } public void testRepeatedOnce() { Test test = new RepeatedTest(fSuite, 1); assertEquals(2, test.countTestCases()); TestResult result = new TestResult(); test.run(result); assertEquals(2, result.runCount()); } public void testRepeatedMoreThanOnce() { Test test = new RepeatedTest(fSuite, 3); assertEquals(6, test.countTestCases()); TestResult result = new TestResult(); test.run(result); assertEquals(6, result.runCount()); } public void testRepeatedZero() { Test test = new RepeatedTest(fSuite, 0); assertEquals(0, test.countTestCases()); TestResult result = new TestResult(); test.run(result); assertEquals(0, result.runCount()); } public void testRepeatedNegative() { try { new RepeatedTest(fSuite, -1); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains(">=")); return; } fail("Should throw an IllegalArgumentException"); } }junit4-4.11/src/test/java/junit/tests/extensions/ExtensionTest.java0000644000175000017500000000462412050524441025047 0ustar ebourgebourgpackage junit.tests.extensions; import junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestResult; import junit.framework.TestSuite; import junit.tests.WasRun; /** * A test case testing the extensions to the testing framework. */ public class ExtensionTest extends TestCase { static class TornDown extends TestSetup { boolean fTornDown = false; TornDown(Test test) { super(test); } @Override protected void tearDown() { fTornDown = true; } } public void testRunningErrorInTestSetup() { TestCase test = new TestCase("failure") { @Override public void runTest() { fail(); } }; TestSetup wrapper = new TestSetup(test); TestResult result = new TestResult(); wrapper.run(result); assertTrue(!result.wasSuccessful()); } public void testRunningErrorsInTestSetup() { TestCase failure = new TestCase("failure") { @Override public void runTest() { fail(); } }; TestCase error = new TestCase("error") { @Override public void runTest() { throw new Error(); } }; TestSuite suite = new TestSuite(); suite.addTest(failure); suite.addTest(error); TestSetup wrapper = new TestSetup(suite); TestResult result = new TestResult(); wrapper.run(result); assertEquals(1, result.failureCount()); assertEquals(1, result.errorCount()); } public void testSetupErrorDontTearDown() { WasRun test = new WasRun(); TornDown wrapper = new TornDown(test) { @Override public void setUp() { fail(); } }; TestResult result = new TestResult(); wrapper.run(result); assertTrue(!wrapper.fTornDown); } public void testSetupErrorInTestSetup() { WasRun test = new WasRun(); TestSetup wrapper = new TestSetup(test) { @Override public void setUp() { fail(); } }; TestResult result = new TestResult(); wrapper.run(result); assertTrue(!test.fWasRun); assertTrue(!result.wasSuccessful()); } }junit4-4.11/src/test/java/junit/tests/extensions/ActiveTestTest.java0000644000175000017500000000361412050524441025144 0ustar ebourgebourgpackage junit.tests.extensions; import junit.extensions.ActiveTestSuite; import junit.extensions.RepeatedTest; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestResult; /** * Testing the ActiveTest support */ public class ActiveTestTest extends TestCase { public static class SuccessTest extends TestCase { @Override public void runTest() { } } public void testActiveTest() { Test test = createActiveTestSuite(); TestResult result = new TestResult(); test.run(result); assertEquals(100, result.runCount()); assertEquals(0, result.failureCount()); assertEquals(0, result.errorCount()); } public void testActiveRepeatedTest() { Test test = new RepeatedTest(createActiveTestSuite(), 5); TestResult result = new TestResult(); test.run(result); assertEquals(500, result.runCount()); assertEquals(0, result.failureCount()); assertEquals(0, result.errorCount()); } public void testActiveRepeatedTest0() { Test test = new RepeatedTest(createActiveTestSuite(), 0); TestResult result = new TestResult(); test.run(result); assertEquals(0, result.runCount()); assertEquals(0, result.failureCount()); assertEquals(0, result.errorCount()); } public void testActiveRepeatedTest1() { Test test = new RepeatedTest(createActiveTestSuite(), 1); TestResult result = new TestResult(); test.run(result); assertEquals(100, result.runCount()); assertEquals(0, result.failureCount()); assertEquals(0, result.errorCount()); } ActiveTestSuite createActiveTestSuite() { ActiveTestSuite suite = new ActiveTestSuite(); for (int i = 0; i < 100; i++) { suite.addTest(new SuccessTest()); } return suite; } }junit4-4.11/src/test/java/junit/tests/extensions/AllTests.java0000644000175000017500000000115412050524441023761 0ustar ebourgebourgpackage junit.tests.extensions; import junit.framework.Test; import junit.framework.TestSuite; /** * TestSuite that runs all the extension tests */ public class AllTests { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { // Collect tests manually because we have to test class collection code TestSuite suite = new TestSuite("Framework Tests"); suite.addTestSuite(ExtensionTest.class); suite.addTestSuite(ActiveTestTest.class); suite.addTestSuite(RepeatedTestTest.class); return suite; } }junit4-4.11/src/test/java/junit/tests/framework/0000755000175000017500000000000012050524441021160 5ustar ebourgebourgjunit4-4.11/src/test/java/junit/tests/framework/package-info.java0000644000175000017500000000011412050524441024343 0ustar ebourgebourg/** * Tests the JUnit v3.x core classes. */ package junit.tests.framework;junit4-4.11/src/test/java/junit/tests/framework/InheritedTestCase.java0000644000175000017500000000023612050524441025373 0ustar ebourgebourgpackage junit.tests.framework; /** * Test class used in SuiteTest */ public class InheritedTestCase extends OneTestCase { public void test2() { } }junit4-4.11/src/test/java/junit/tests/framework/AssertTest.java0000644000175000017500000001053312050524441024126 0ustar ebourgebourgpackage junit.tests.framework; import junit.framework.AssertionFailedError; import junit.framework.ComparisonFailure; import junit.framework.TestCase; public class AssertTest extends TestCase { /* In the tests that follow, we can't use standard formatting * for exception tests: * try { * somethingThatShouldThrow(); * fail(); * catch (AssertionFailedError e) { * } * because fail() would never be reported. */ public void testFail() { // Also, we are testing fail, so we can't rely on fail() working. // We have to throw the exception manually. try { fail(); } catch (AssertionFailedError e) { return; } throw new AssertionFailedError(); } public void testAssertionFailedErrorToStringWithNoMessage() { // Also, we are testing fail, so we can't rely on fail() working. // We have to throw the exception manually. try { fail(); } catch (AssertionFailedError e) { assertEquals("junit.framework.AssertionFailedError", e.toString()); return; } throw new AssertionFailedError(); } public void testAssertionFailedErrorToStringWithMessage() { // Also, we are testing fail, so we can't rely on fail() working. // We have to throw the exception manually. try { fail("woops!"); } catch (AssertionFailedError e) { assertEquals("junit.framework.AssertionFailedError: woops!", e.toString()); return; } throw new AssertionFailedError(); } public void testAssertEquals() { Object o = new Object(); assertEquals(o, o); try { assertEquals(new Object(), new Object()); } catch (AssertionFailedError e) { return; } fail(); } public void testAssertEqualsNull() { assertEquals((Object) null, (Object) null); } public void testAssertStringEquals() { assertEquals("a", "a"); } public void testAssertNullNotEqualsString() { try { assertEquals(null, "foo"); fail(); } catch (ComparisonFailure e) { } } public void testAssertStringNotEqualsNull() { try { assertEquals("foo", null); fail(); } catch (ComparisonFailure e) { e.getMessage(); // why no assertion? } } public void testAssertNullNotEqualsNull() { try { assertEquals(null, new Object()); } catch (AssertionFailedError e) { e.getMessage(); // why no assertion? return; } fail(); } public void testAssertNull() { assertNull(null); try { assertNull(new Object()); } catch (AssertionFailedError e) { return; } fail(); } public void testAssertNotNull() { assertNotNull(new Object()); try { assertNotNull(null); } catch (AssertionFailedError e) { return; } fail(); } public void testAssertTrue() { assertTrue(true); try { assertTrue(false); } catch (AssertionFailedError e) { return; } fail(); } public void testAssertFalse() { assertFalse(false); try { assertFalse(true); } catch (AssertionFailedError e) { return; } fail(); } public void testAssertSame() { Object o = new Object(); assertSame(o, o); try { assertSame(new Integer(1), new Integer(1)); } catch (AssertionFailedError e) { return; } fail(); } public void testAssertNotSame() { assertNotSame(new Integer(1), null); assertNotSame(null, new Integer(1)); assertNotSame(new Integer(1), new Integer(1)); try { Integer obj = new Integer(1); assertNotSame(obj, obj); } catch (AssertionFailedError e) { return; } fail(); } public void testAssertNotSameFailsNull() { try { assertNotSame(null, null); } catch (AssertionFailedError e) { return; } fail(); } }junit4-4.11/src/test/java/junit/tests/framework/NoArgTestCaseTest.java0000644000175000017500000000031212050524441025321 0ustar ebourgebourgpackage junit.tests.framework; import junit.framework.TestCase; public class NoArgTestCaseTest extends TestCase { public void testNothing() { // If this compiles, the no arg ctor is there } } junit4-4.11/src/test/java/junit/tests/framework/SuiteTest.java0000644000175000017500000001004512050524441023754 0ustar ebourgebourgpackage junit.tests.framework; import java.util.Collections; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestResult; import junit.framework.TestSuite; /** * A fixture for testing the "auto" test suite feature. */ public class SuiteTest extends TestCase { protected TestResult fResult; public SuiteTest(String name) { super(name); } @Override protected void setUp() { fResult = new TestResult(); } public static Test suite() { TestSuite suite = new TestSuite("Suite Tests"); // build the suite manually, because some of the suites are testing // the functionality that automatically builds suites suite.addTest(new SuiteTest("testNoTestCases")); suite.addTest(new SuiteTest("testOneTestCase")); suite.addTest(new SuiteTest("testNotPublicTestCase")); suite.addTest(new SuiteTest("testNotVoidTestCase")); suite.addTest(new SuiteTest("testNotExistingTestCase")); suite.addTest(new SuiteTest("testInheritedTests")); suite.addTest(new SuiteTest("testOneTestCaseEclipseSeesSameStructureAs381")); suite.addTest(new SuiteTest("testNoTestCaseClass")); suite.addTest(new SuiteTest("testShadowedTests")); suite.addTest(new SuiteTest("testAddTestSuite")); suite.addTest(new SuiteTest("testCreateSuiteFromArray")); return suite; } public void testInheritedTests() { TestSuite suite = new TestSuite(InheritedTestCase.class); suite.run(fResult); assertTrue(fResult.wasSuccessful()); assertEquals(2, fResult.runCount()); } public void testNoTestCaseClass() { Test t = new TestSuite(NoTestCaseClass.class); t.run(fResult); assertEquals(1, fResult.runCount()); // warning test assertTrue(!fResult.wasSuccessful()); } public void testNoTestCases() { Test t = new TestSuite(NoTestCases.class); t.run(fResult); assertTrue(fResult.runCount() == 1); // warning test assertTrue(fResult.failureCount() == 1); assertTrue(!fResult.wasSuccessful()); } public void testNotExistingTestCase() { Test t = new SuiteTest("notExistingMethod"); t.run(fResult); assertTrue(fResult.runCount() == 1); assertTrue(fResult.failureCount() == 1); assertTrue(fResult.errorCount() == 0); } public void testNotPublicTestCase() { TestSuite suite = new TestSuite(NotPublicTestCase.class); // 1 public test case + 1 warning for the non-public test case assertEquals(2, suite.countTestCases()); } public void testNotVoidTestCase() { TestSuite suite = new TestSuite(NotVoidTestCase.class); assertTrue(suite.countTestCases() == 1); } public void testOneTestCase() { TestSuite t = new TestSuite(OneTestCase.class); t.run(fResult); assertTrue(fResult.runCount() == 1); assertTrue(fResult.failureCount() == 0); assertTrue(fResult.errorCount() == 0); assertTrue(fResult.wasSuccessful()); } public void testOneTestCaseEclipseSeesSameStructureAs381() { TestSuite t = new TestSuite(ThreeTestCases.class); assertEquals(3, Collections.list(t.tests()).size()); } public void testShadowedTests() { TestSuite suite = new TestSuite(OverrideTestCase.class); suite.run(fResult); assertEquals(1, fResult.runCount()); } public void testAddTestSuite() { TestSuite suite = new TestSuite(); suite.addTestSuite(OneTestCase.class); suite.run(fResult); assertEquals(1, fResult.runCount()); } public void testCreateSuiteFromArray() { TestSuite suite = new TestSuite(OneTestCase.class, DoublePrecisionAssertTest.class); assertEquals(2, suite.testCount()); assertEquals("junit.tests.framework.DoublePrecisionAssertTest", ((TestSuite) suite.testAt(1)).getName()); assertEquals("junit.tests.framework.OneTestCase", ((TestSuite) suite.testAt(0)).getName()); } }junit4-4.11/src/test/java/junit/tests/framework/AssertionFailedErrorTest.java0000644000175000017500000000150612050524441026753 0ustar ebourgebourgpackage junit.tests.framework; import junit.framework.AssertionFailedError; import junit.framework.TestCase; public class AssertionFailedErrorTest extends TestCase { private static final String ARBITRARY_MESSAGE = "arbitrary message"; public void testCreateErrorWithoutMessage() throws Exception { AssertionFailedError error = new AssertionFailedError(); assertNull(error.getMessage()); } public void testCreateErrorWithMessage() throws Exception { AssertionFailedError error = new AssertionFailedError(ARBITRARY_MESSAGE); assertEquals(ARBITRARY_MESSAGE, error.getMessage()); } public void testCreateErrorWithoutMessageInsteadOfNull() throws Exception { AssertionFailedError error = new AssertionFailedError(null); assertEquals("", error.getMessage()); } } junit4-4.11/src/test/java/junit/tests/framework/Failure.java0000644000175000017500000000034112050524441023410 0ustar ebourgebourgpackage junit.tests.framework; import junit.framework.TestCase; /** * A test case testing the testing framework. */ public class Failure extends TestCase { @Override public void runTest() { fail(); } }junit4-4.11/src/test/java/junit/tests/framework/NotPublicTestCase.java0000644000175000017500000000035612050524441025362 0ustar ebourgebourgpackage junit.tests.framework; import junit.framework.TestCase; /** * Test class used in SuiteTest */ public class NotPublicTestCase extends TestCase { protected void testNotPublic() { } public void testPublic() { } }junit4-4.11/src/test/java/junit/tests/framework/TestImplementorTest.java0000644000175000017500000000272212050524441026021 0ustar ebourgebourgpackage junit.tests.framework; import junit.framework.Protectable; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestResult; /** * Test an implementor of junit.framework.Test other than TestCase or TestSuite */ public class TestImplementorTest extends TestCase { public static class DoubleTestCase implements Test { private TestCase fTestCase; public DoubleTestCase(TestCase testCase) { fTestCase = testCase; } public int countTestCases() { return 2; } public void run(TestResult result) { result.startTest(this); Protectable p = new Protectable() { public void protect() throws Throwable { fTestCase.runBare(); fTestCase.runBare(); } }; result.runProtected(this, p); result.endTest(this); } } private DoubleTestCase fTest; public TestImplementorTest() { TestCase testCase = new TestCase() { @Override public void runTest() { } }; fTest = new DoubleTestCase(testCase); } public void testSuccessfulRun() { TestResult result = new TestResult(); fTest.run(result); assertEquals(fTest.countTestCases(), result.runCount()); assertEquals(0, result.errorCount()); assertEquals(0, result.failureCount()); } } junit4-4.11/src/test/java/junit/tests/framework/OneTestCase.java0000644000175000017500000000041312050524441024176 0ustar ebourgebourgpackage junit.tests.framework; import junit.framework.TestCase; /** * Test class used in SuiteTest */ public class OneTestCase extends TestCase { public void noTestCase() { } public void testCase() { } public void testCase(int arg) { } }junit4-4.11/src/test/java/junit/tests/framework/NotVoidTestCase.java0000644000175000017500000000036612050524441025046 0ustar ebourgebourgpackage junit.tests.framework; import junit.framework.TestCase; /** * Test class used in SuiteTest */ public class NotVoidTestCase extends TestCase { public int testNotVoid() { return 1; } public void testVoid() { } }junit4-4.11/src/test/java/junit/tests/framework/FloatAssertTest.java0000644000175000017500000000317312050524441025116 0ustar ebourgebourgpackage junit.tests.framework; import junit.framework.AssertionFailedError; import junit.framework.TestCase; public class FloatAssertTest extends TestCase { /** * Test for the special Double.NaN value. */ public void testAssertEqualsNaNFails() { try { assertEquals(1.234f, Float.NaN, 0.0); fail(); } catch (AssertionFailedError e) { } } public void testAssertNaNEqualsFails() { try { assertEquals(Float.NaN, 1.234f, 0.0); fail(); } catch (AssertionFailedError e) { } } public void testAssertNaNEqualsNaN() { assertEquals(Float.NaN, Float.NaN, 0.0); } public void testAssertPosInfinityNotEqualsNegInfinity() { try { assertEquals(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, 0.0); fail(); } catch (AssertionFailedError e) { } } public void testAssertPosInfinityNotEquals() { try { assertEquals(Float.POSITIVE_INFINITY, 1.23f, 0.0); fail(); } catch (AssertionFailedError e) { } } public void testAssertPosInfinityEqualsInfinity() { assertEquals(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, 0.0); } public void testAssertNegInfinityEqualsInfinity() { assertEquals(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY, 0.0); } public void testAllInfinities() { try { assertEquals(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY); fail(); } catch (AssertionFailedError e) { } } } junit4-4.11/src/test/java/junit/tests/framework/DoublePrecisionAssertTest.java0000644000175000017500000000264412050524441027141 0ustar ebourgebourgpackage junit.tests.framework; import junit.framework.AssertionFailedError; import junit.framework.TestCase; public class DoublePrecisionAssertTest extends TestCase { /** * Test for the special Double.NaN value. */ public void testAssertEqualsNaNFails() { try { assertEquals(1.234, Double.NaN, 0.0); fail(); } catch (AssertionFailedError e) { } } public void testAssertNaNEqualsFails() { try { assertEquals(Double.NaN, 1.234, 0.0); fail(); } catch (AssertionFailedError e) { } } public void testAssertNaNEqualsNaN() { assertEquals(Double.NaN, Double.NaN, 0.0); } public void testAssertPosInfinityNotEqualsNegInfinity() { try { assertEquals(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 0.0); fail(); } catch (AssertionFailedError e) { } } public void testAssertPosInfinityNotEquals() { try { assertEquals(Double.POSITIVE_INFINITY, 1.23, 0.0); fail(); } catch (AssertionFailedError e) { } } public void testAssertPosInfinityEqualsInfinity() { assertEquals(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, 0.0); } public void testAssertNegInfinityEqualsInfinity() { assertEquals(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY, 0.0); } } junit4-4.11/src/test/java/junit/tests/framework/TestListenerTest.java0000644000175000017500000000352612050524441025316 0ustar ebourgebourgpackage junit.tests.framework; import junit.framework.AssertionFailedError; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestListener; import junit.framework.TestResult; /** * Test class used in SuiteTest */ public class TestListenerTest extends TestCase implements TestListener { private TestResult fResult; private int fStartCount; private int fEndCount; private int fFailureCount; private int fErrorCount; public void addError(Test test, Throwable t) { fErrorCount++; } public void addFailure(Test test, AssertionFailedError t) { fFailureCount++; } public void endTest(Test test) { fEndCount++; } @Override protected void setUp() { fResult = new TestResult(); fResult.addListener(this); fStartCount = 0; fEndCount = 0; fFailureCount = 0; fErrorCount = 0; } public void startTest(Test test) { fStartCount++; } public void testError() { TestCase test = new TestCase("noop") { @Override public void runTest() { throw new Error(); } }; test.run(fResult); assertEquals(1, fErrorCount); assertEquals(1, fEndCount); } public void testFailure() { TestCase test = new TestCase("noop") { @Override public void runTest() { fail(); } }; test.run(fResult); assertEquals(1, fFailureCount); assertEquals(1, fEndCount); } public void testStartStop() { TestCase test = new TestCase("noop") { @Override public void runTest() { } }; test.run(fResult); assertEquals(1, fStartCount); assertEquals(1, fEndCount); } }junit4-4.11/src/test/java/junit/tests/framework/OverrideTestCase.java0000644000175000017500000000025612050524441025241 0ustar ebourgebourgpackage junit.tests.framework; /** * Test class used in SuiteTest */ public class OverrideTestCase extends OneTestCase { @Override public void testCase() { } }junit4-4.11/src/test/java/junit/tests/framework/ComparisonCompactorTest.java0000644000175000017500000000776012050524441026657 0ustar ebourgebourgpackage junit.tests.framework; import junit.framework.ComparisonCompactor; import junit.framework.TestCase; public class ComparisonCompactorTest extends TestCase { public void testMessage() { String failure = new ComparisonCompactor(0, "b", "c").compact("a"); assertTrue("a expected:<[b]> but was:<[c]>".equals(failure)); } public void testStartSame() { String failure = new ComparisonCompactor(1, "ba", "bc").compact(null); assertEquals("expected: but was:", failure); } public void testEndSame() { String failure = new ComparisonCompactor(1, "ab", "cb").compact(null); assertEquals("expected:<[a]b> but was:<[c]b>", failure); } public void testSame() { String failure = new ComparisonCompactor(1, "ab", "ab").compact(null); assertEquals("expected: but was:", failure); } public void testNoContextStartAndEndSame() { String failure = new ComparisonCompactor(0, "abc", "adc").compact(null); assertEquals("expected:<...[b]...> but was:<...[d]...>", failure); } public void testStartAndEndContext() { String failure = new ComparisonCompactor(1, "abc", "adc").compact(null); assertEquals("expected: but was:", failure); } public void testStartAndEndContextWithEllipses() { String failure = new ComparisonCompactor(1, "abcde", "abfde").compact(null); assertEquals("expected:<...b[c]d...> but was:<...b[f]d...>", failure); } public void testComparisonErrorStartSameComplete() { String failure = new ComparisonCompactor(2, "ab", "abc").compact(null); assertEquals("expected: but was:", failure); } public void testComparisonErrorEndSameComplete() { String failure = new ComparisonCompactor(0, "bc", "abc").compact(null); assertEquals("expected:<[]...> but was:<[a]...>", failure); } public void testComparisonErrorEndSameCompleteContext() { String failure = new ComparisonCompactor(2, "bc", "abc").compact(null); assertEquals("expected:<[]bc> but was:<[a]bc>", failure); } public void testComparisonErrorOverlapingMatches() { String failure = new ComparisonCompactor(0, "abc", "abbc").compact(null); assertEquals("expected:<...[]...> but was:<...[b]...>", failure); } public void testComparisonErrorOverlapingMatchesContext() { String failure = new ComparisonCompactor(2, "abc", "abbc").compact(null); assertEquals("expected: but was:", failure); } public void testComparisonErrorOverlapingMatches2() { String failure = new ComparisonCompactor(0, "abcdde", "abcde").compact(null); assertEquals("expected:<...[d]...> but was:<...[]...>", failure); } public void testComparisonErrorOverlapingMatches2Context() { String failure = new ComparisonCompactor(2, "abcdde", "abcde").compact(null); assertEquals("expected:<...cd[d]e> but was:<...cd[]e>", failure); } public void testComparisonErrorWithActualNull() { String failure = new ComparisonCompactor(0, "a", null).compact(null); assertEquals("expected:
    but was:", failure); } public void testComparisonErrorWithActualNullContext() { String failure = new ComparisonCompactor(2, "a", null).compact(null); assertEquals("expected: but was:", failure); } public void testComparisonErrorWithExpectedNull() { String failure = new ComparisonCompactor(0, null, "a").compact(null); assertEquals("expected: but was:", failure); } public void testComparisonErrorWithExpectedNullContext() { String failure = new ComparisonCompactor(2, null, "a").compact(null); assertEquals("expected: but was:", failure); } public void testBug609972() { String failure = new ComparisonCompactor(10, "S&P500", "0").compact(null); assertEquals("expected:<[S&P50]0> but was:<[]0>", failure); } } junit4-4.11/src/test/java/junit/tests/framework/NoTestCases.java0000644000175000017500000000027412050524441024221 0ustar ebourgebourgpackage junit.tests.framework; import junit.framework.TestCase; /** * Test class used in SuiteTest */ public class NoTestCases extends TestCase { public void noTestCase() { } }junit4-4.11/src/test/java/junit/tests/framework/ComparisonFailureTest.java0000644000175000017500000000266012050524441026311 0ustar ebourgebourgpackage junit.tests.framework; import junit.framework.ComparisonFailure; import junit.framework.TestCase; public class ComparisonFailureTest extends TestCase { // Most of the tests are in ComparisonCompactorTest public void testConnection() { ComparisonFailure failure = new ComparisonFailure("warning", "Mary had a little lamb", "Mary had the little lamb"); assertEquals("warning expected: but was:", failure.getMessage()); } // This is like an instanceof test. public void testThrowing() { try { assertEquals("a", "b"); } catch (ComparisonFailure e) { return; } fail(); } public void testExceptionToStringWithMessage() { try { assertEquals("woops!", "a", "b"); } catch (ComparisonFailure e) { if (!e.toString().startsWith("junit.framework.ComparisonFailure: woops! expected:<")) { fail("Unexpected message: " + e); } return; } fail(); } public void testExceptionToStringWithoutMessage() { try { assertEquals("a", "b"); } catch (ComparisonFailure e) { if (!e.toString().startsWith("junit.framework.ComparisonFailure: expected:<")) { fail("Unexpected message: " + e); } return; } fail(); } } junit4-4.11/src/test/java/junit/tests/framework/TestCaseTest.java0000644000175000017500000001264012050524441024401 0ustar ebourgebourgpackage junit.tests.framework; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestFailure; import junit.framework.TestResult; import junit.framework.TestSuite; import junit.tests.WasRun; /** * A test case testing the testing framework. */ public class TestCaseTest extends TestCase { static class TornDown extends TestCase { boolean fTornDown = false; @Override protected void tearDown() { fTornDown = true; } @Override protected void runTest() { throw new Error("running"); } } public void testCaseToString() { // This test wins the award for twisted snake tail eating while // writing self tests. And you thought those weird anonymous // inner classes were bad... assertEquals("testCaseToString(junit.tests.framework.TestCaseTest)", toString()); } public void testError() { TestCase error = new TestCase("error") { @Override protected void runTest() { throw new Error(); } }; verifyError(error); } public void testRunAndTearDownFails() { TornDown fails = new TornDown() { @Override protected void tearDown() { super.tearDown(); throw new Error(); } @Override protected void runTest() { throw new Error(); } }; verifyError(fails); assertTrue(fails.fTornDown); } public void testSetupFails() { TestCase fails = new TestCase("success") { @Override protected void setUp() { throw new Error(); } @Override protected void runTest() { } }; verifyError(fails); } public void testSuccess() { TestCase success = new TestCase("success") { @Override protected void runTest() { } }; verifySuccess(success); } public void testFailure() { TestCase failure = new TestCase("failure") { @Override protected void runTest() { fail(); } }; verifyFailure(failure); } public void testTearDownAfterError() { TornDown fails = new TornDown(); verifyError(fails); assertTrue(fails.fTornDown); } public void testTearDownFails() { TestCase fails = new TestCase("success") { @Override protected void tearDown() { throw new Error(); } @Override protected void runTest() { } }; verifyError(fails); } public void testTearDownSetupFails() { TornDown fails = new TornDown() { @Override protected void setUp() { throw new Error(); } }; verifyError(fails); assertTrue(!fails.fTornDown); } public void testWasRun() { WasRun test = new WasRun(); test.run(); assertTrue(test.fWasRun); } public void testExceptionRunningAndTearDown() { // With 1.4, we should // wrap the exception thrown while running with the exception thrown // while tearing down Test t = new TornDown() { @Override public void tearDown() { throw new Error("tearingDown"); } }; TestResult result = new TestResult(); t.run(result); TestFailure failure = result.errors().nextElement(); assertEquals("running", failure.thrownException().getMessage()); } public void testErrorTearingDownDoesntMaskErrorRunning() { final Exception running = new Exception("Running"); TestCase t = new TestCase() { @Override protected void runTest() throws Throwable { throw running; } @Override protected void tearDown() throws Exception { throw new Error("Tearing down"); } }; try { t.runBare(); } catch (Throwable thrown) { assertSame(running, thrown); } } public void testNoArgTestCasePasses() { Test t = new TestSuite(NoArgTestCaseTest.class); TestResult result = new TestResult(); t.run(result); assertTrue(result.runCount() == 1); assertTrue(result.failureCount() == 0); assertTrue(result.errorCount() == 0); } public void testNamelessTestCase() { TestCase t = new TestCase() { }; TestResult result = t.run(); assertEquals(1, result.failureCount()); } void verifyError(TestCase test) { TestResult result = test.run(); assertTrue(result.runCount() == 1); assertTrue(result.failureCount() == 0); assertTrue(result.errorCount() == 1); } void verifyFailure(TestCase test) { TestResult result = test.run(); assertTrue(result.runCount() == 1); assertTrue(result.failureCount() == 1); assertTrue(result.errorCount() == 0); } void verifySuccess(TestCase test) { TestResult result = test.run(); assertTrue(result.runCount() == 1); assertTrue(result.failureCount() == 0); assertTrue(result.errorCount() == 0); } }junit4-4.11/src/test/java/junit/tests/framework/NoTestCaseClass.java0000644000175000017500000000023512050524441025021 0ustar ebourgebourgpackage junit.tests.framework; /** * Test class used in SuiteTest */ public class NoTestCaseClass extends Object { public void testSuccess() { } }junit4-4.11/src/test/java/junit/tests/framework/Success.java0000644000175000017500000000037112050524441023434 0ustar ebourgebourgpackage junit.tests.framework; import junit.framework.TestCase; /** * A test case testing the testing framework. */ public class Success extends TestCase { @Override public void runTest() { } public void testSuccess() { } }junit4-4.11/src/test/java/junit/tests/framework/ThreeTestCases.java0000644000175000017500000000043212050524441024710 0ustar ebourgebourgpackage junit.tests.framework; import junit.framework.TestCase; /** * Test class used in SuiteTest */ public class ThreeTestCases extends TestCase { public void testCase() { } public void testCase2() { } public void testCase3thisTimeItsPersonal() { } }junit4-4.11/src/test/java/junit/tests/framework/AllTests.java0000644000175000017500000000202212050524441023552 0ustar ebourgebourgpackage junit.tests.framework; import junit.framework.Test; import junit.framework.TestSuite; /** * TestSuite that runs all the sample tests */ public class AllTests { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { TestSuite suite = new TestSuite("Framework Tests"); suite.addTestSuite(TestCaseTest.class); suite.addTest(SuiteTest.suite()); // Tests suite building, so can't use automatic test extraction suite.addTestSuite(TestListenerTest.class); suite.addTestSuite(AssertionFailedErrorTest.class); suite.addTestSuite(AssertTest.class); suite.addTestSuite(TestImplementorTest.class); suite.addTestSuite(NoArgTestCaseTest.class); suite.addTestSuite(ComparisonCompactorTest.class); suite.addTestSuite(ComparisonFailureTest.class); suite.addTestSuite(DoublePrecisionAssertTest.class); suite.addTestSuite(FloatAssertTest.class); return suite; } }junit4-4.11/src/test/java/junit/tests/WasRun.java0000644000175000017500000000044012050524441021243 0ustar ebourgebourgpackage junit.tests; import junit.framework.TestCase; /** * A helper test case for testing whether the testing method * is run. */ public class WasRun extends TestCase { public boolean fWasRun = false; @Override protected void runTest() { fWasRun = true; } }junit4-4.11/src/test/java/junit/tests/runner/0000755000175000017500000000000012050524441020474 5ustar ebourgebourgjunit4-4.11/src/test/java/junit/tests/runner/package-info.java0000644000175000017500000000012512050524441023661 0ustar ebourgebourg/** * Tests for the JUnit v3.x runner functionality. */ package junit.tests.runner;junit4-4.11/src/test/java/junit/tests/runner/ResultTest.java0000644000175000017500000000262312050524441023460 0ustar ebourgebourgpackage junit.tests.runner; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import junit.framework.TestCase; import junit.tests.framework.Success; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.tests.running.methods.AnnotationTest; public class ResultTest extends TestCase { public void testRunFailureResultCanBeSerialised() throws Exception { JUnitCore runner = new JUnitCore(); Result result = runner.run(AnnotationTest.FailureTest.class); assertResultSerializable(result); } public void testRunSuccessResultCanBeSerialised() throws Exception { JUnitCore runner = new JUnitCore(); Result result = runner.run(Success.class); assertResultSerializable(result); } private void assertResultSerializable(Result result) throws IOException, ClassNotFoundException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); new ObjectOutputStream(byteArrayOutputStream).writeObject(result); byte[] bytes = byteArrayOutputStream.toByteArray(); ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes)); Result fromStream = (Result) objectInputStream.readObject(); assertNotNull(fromStream); } } junit4-4.11/src/test/java/junit/tests/runner/TextFeedbackTest.java0000644000175000017500000000762612050524441024543 0ustar ebourgebourgpackage junit.tests.runner; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.io.PrintStream; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import junit.framework.TestResult; import junit.framework.TestSuite; import junit.textui.ResultPrinter; import junit.textui.TestRunner; public class TextFeedbackTest extends TestCase { OutputStream output; TestRunner runner; static class TestResultPrinter extends ResultPrinter { TestResultPrinter(PrintStream writer) { super(writer); } /* Spoof printing time so the tests are deterministic */ @Override protected String elapsedTimeAsString(long runTime) { return "0"; } } public static void main(String[] args) { TestRunner.run(TextFeedbackTest.class); } @Override public void setUp() { output = new ByteArrayOutputStream(); runner = new TestRunner(new TestResultPrinter(new PrintStream(output))); } public void testEmptySuite() { String expected = expected(new String[]{"", "Time: 0", "", "OK (0 tests)", ""}); runner.doRun(new TestSuite()); assertEquals(expected, output.toString()); } public void testOneTest() { String expected = expected(new String[]{".", "Time: 0", "", "OK (1 test)", ""}); TestSuite suite = new TestSuite(); suite.addTest(new TestCase() { @Override public void runTest() { } }); runner.doRun(suite); assertEquals(expected, output.toString()); } public void testTwoTests() { String expected = expected(new String[]{"..", "Time: 0", "", "OK (2 tests)", ""}); TestSuite suite = new TestSuite(); suite.addTest(new TestCase() { @Override public void runTest() { } }); suite.addTest(new TestCase() { @Override public void runTest() { } }); runner.doRun(suite); assertEquals(expected, output.toString()); } public void testFailure() { String expected = expected(new String[]{".F", "Time: 0", "Failures here", "", "FAILURES!!!", "Tests run: 1, Failures: 1, Errors: 0", ""}); ResultPrinter printer = new TestResultPrinter(new PrintStream(output)) { @Override public void printFailures(TestResult result) { getWriter().println("Failures here"); } }; runner.setPrinter(printer); TestSuite suite = new TestSuite(); suite.addTest(new TestCase() { @Override public void runTest() { throw new AssertionFailedError(); } }); runner.doRun(suite); assertEquals(expected, output.toString()); } public void testError() { String expected = expected(new String[]{".E", "Time: 0", "Errors here", "", "FAILURES!!!", "Tests run: 1, Failures: 0, Errors: 1", ""}); ResultPrinter printer = new TestResultPrinter(new PrintStream(output)) { @Override public void printErrors(TestResult result) { getWriter().println("Errors here"); } }; runner.setPrinter(printer); TestSuite suite = new TestSuite(); suite.addTest(new TestCase() { @Override public void runTest() throws Exception { throw new Exception(); } }); runner.doRun(suite); assertEquals(expected, output.toString()); } private String expected(String[] lines) { OutputStream expected = new ByteArrayOutputStream(); PrintStream expectedWriter = new PrintStream(expected); for (int i = 0; i < lines.length; i++) { expectedWriter.println(lines[i]); } return expected.toString(); } } junit4-4.11/src/test/java/junit/tests/runner/StackFilterTest.java0000644000175000017500000000410312050524441024410 0ustar ebourgebourgpackage junit.tests.runner; import java.io.PrintWriter; import java.io.StringWriter; import junit.framework.TestCase; import junit.runner.BaseTestRunner; public class StackFilterTest extends TestCase { String fFiltered; String fUnfiltered; @Override protected void setUp() { StringWriter swin = new StringWriter(); PrintWriter pwin = new PrintWriter(swin); pwin.println("junit.framework.AssertionFailedError"); pwin.println(" at junit.framework.Assert.fail(Assert.java:144)"); pwin.println(" at junit.framework.Assert.assert(Assert.java:19)"); pwin.println(" at junit.framework.Assert.assert(Assert.java:26)"); pwin.println(" at MyTest.f(MyTest.java:13)"); pwin.println(" at MyTest.testStackTrace(MyTest.java:8)"); pwin.println(" at java.lang.reflect.Method.invoke(Native Method)"); pwin.println(" at junit.framework.TestCase.runTest(TestCase.java:156)"); pwin.println(" at junit.framework.TestCase.runBare(TestCase.java:130)"); pwin.println(" at junit.framework.TestResult$1.protect(TestResult.java:100)"); pwin.println(" at junit.framework.TestResult.runProtected(TestResult.java:118)"); pwin.println(" at junit.framework.TestResult.run(TestResult.java:103)"); pwin.println(" at junit.framework.TestCase.run(TestCase.java:121)"); pwin.println(" at junit.framework.TestSuite.runTest(TestSuite.java:157)"); pwin.println(" at junit.framework.TestSuite.run(TestSuite.java, Compiled Code)"); pwin.println(" at junit.swingui.TestRunner$17.run(TestRunner.java:669)"); fUnfiltered = swin.toString(); StringWriter swout = new StringWriter(); PrintWriter pwout = new PrintWriter(swout); pwout.println("junit.framework.AssertionFailedError"); pwout.println(" at MyTest.f(MyTest.java:13)"); pwout.println(" at MyTest.testStackTrace(MyTest.java:8)"); fFiltered = swout.toString(); } public void testFilter() { assertEquals(fFiltered, BaseTestRunner.getFilteredTrace(fUnfiltered)); } }junit4-4.11/src/test/java/junit/tests/runner/BaseTestRunnerTest.java0000644000175000017500000000252612050524441025110 0ustar ebourgebourgpackage junit.tests.runner; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.runner.BaseTestRunner; public class BaseTestRunnerTest extends TestCase { public static class MockRunner extends BaseTestRunner { private boolean fRunFailed = false; @Override protected void runFailed(String message) { fRunFailed = true; } @Override public void testEnded(String testName) { } @Override public void testFailed(int status, Test test, Throwable t) { } @Override public void testStarted(String testName) { } } public static class NonStatic { public Test suite() { return null; } } public void testInvokeNonStaticSuite() { BaseTestRunner runner = new MockRunner(); runner.getTest("junit.tests.runner.BaseTestRunnerTest$NonStatic"); // Used to throw NullPointerException } public static class DoesntExtendTestCase { public static Test suite() { return new TestSuite(); } } public void testInvokeSuiteOnNonSubclassOfTestCase() { MockRunner runner = new MockRunner(); runner.getTest(DoesntExtendTestCase.class.getName()); assertFalse(runner.fRunFailed); } } junit4-4.11/src/test/java/junit/tests/runner/TextRunnerSingleMethodTest.java0000644000175000017500000000200212050524441026612 0ustar ebourgebourgpackage junit.tests.runner; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import junit.framework.TestCase; import junit.textui.ResultPrinter; import junit.textui.TestRunner; /** * Test invoking a single test method of a TestCase. */ public class TextRunnerSingleMethodTest extends TestCase { static boolean fgWasInvoked; public static class InvocationTest extends TestCase { public void testWasInvoked() { TextRunnerSingleMethodTest.fgWasInvoked = true; } public void testNotInvoked() { fail("Shouldn't get here."); } } public void testSingle() throws Exception { TestRunner t = new TestRunner(); t.setPrinter(new ResultPrinter(new PrintStream(new ByteArrayOutputStream()))); String[] args = { "-m", "junit.tests.runner.TextRunnerSingleMethodTest$InvocationTest.testWasInvoked" }; fgWasInvoked = false; t.start(args); assertTrue(fgWasInvoked); } }junit4-4.11/src/test/java/junit/tests/runner/TextRunnerTest.java0000644000175000017500000000356512050524441024326 0ustar ebourgebourgpackage junit.tests.runner; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import junit.framework.TestCase; import junit.framework.TestResult; import junit.framework.TestSuite; public class TextRunnerTest extends TestCase { public void testFailure() throws Exception { execTest("junit.tests.framework.Failure", false); } public void testSuccess() throws Exception { execTest("junit.tests.framework.Success", true); } public void testError() throws Exception { execTest("junit.tests.BogusDude", false); } void execTest(String testClass, boolean success) throws Exception { String java = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"; String cp = System.getProperty("java.class.path"); //use -classpath for JDK 1.1.7 compatibility String[] cmd = {java, "-classpath", cp, "junit.textui.TestRunner", testClass}; Process p = Runtime.getRuntime().exec(cmd); InputStream i = p.getInputStream(); while ((i.read()) != -1) ; //System.out.write(b); assertTrue((p.waitFor() == 0) == success); if (success) { assertTrue(p.exitValue() == 0); } else { assertFalse(p.exitValue() == 0); } } public void testRunReturnsResult() { PrintStream oldOut = System.out; System.setOut(new PrintStream( new OutputStream() { @Override public void write(int arg0) throws IOException { } } )); try { TestResult result = junit.textui.TestRunner.run(new TestSuite()); assertTrue(result.wasSuccessful()); } finally { System.setOut(oldOut); } } }junit4-4.11/src/test/java/junit/tests/runner/AllTests.java0000644000175000017500000000162712050524441023100 0ustar ebourgebourgpackage junit.tests.runner; import junit.framework.Test; import junit.framework.TestSuite; /** * TestSuite that runs all the sample tests */ public class AllTests { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { // Collect tests manually because we have to test class collection code TestSuite suite = new TestSuite("Framework Tests"); suite.addTestSuite(StackFilterTest.class); suite.addTestSuite(ResultTest.class); suite.addTestSuite(BaseTestRunnerTest.class); suite.addTestSuite(TextFeedbackTest.class); suite.addTestSuite(TextRunnerSingleMethodTest.class); suite.addTestSuite(TextRunnerTest.class); return suite; } static boolean isJDK11() { String version = System.getProperty("java.version"); return version.startsWith("1.1"); } } junit4-4.11/src/test/java/junit/tests/AllTests.java0000644000175000017500000000107112050524441021560 0ustar ebourgebourgpackage junit.tests; import junit.framework.Test; import junit.framework.TestSuite; /** * TestSuite that runs all the JUnit tests */ public class AllTests { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { TestSuite suite = new TestSuite("Framework Tests"); suite.addTest(junit.tests.framework.AllTests.suite()); suite.addTest(junit.tests.runner.AllTests.suite()); suite.addTest(junit.tests.extensions.AllTests.suite()); return suite; } }junit4-4.11/src/test/java/junit/samples/0000755000175000017500000000000012050524441017465 5ustar ebourgebourgjunit4-4.11/src/test/java/junit/samples/package-info.java0000644000175000017500000000006612050524441022656 0ustar ebourgebourg/** * JUnit v3.x examples. */ package junit.samples;junit4-4.11/src/test/java/junit/samples/money/0000755000175000017500000000000012050524441020614 5ustar ebourgebourgjunit4-4.11/src/test/java/junit/samples/money/package-info.java0000644000175000017500000000010712050524441024001 0ustar ebourgebourg/** * Example "Money" for JUnit v3.x. */ package junit.samples.money;junit4-4.11/src/test/java/junit/samples/money/IMoney.java0000644000175000017500000000227112050524441022661 0ustar ebourgebourgpackage junit.samples.money; /** * The common interface for simple Monies and MoneyBags */ public interface IMoney { /** * Adds a money to this money. */ public abstract IMoney add(IMoney m); /** * Adds a simple Money to this money. This is a helper method for * implementing double dispatch */ public abstract IMoney addMoney(Money m); /** * Adds a MoneyBag to this money. This is a helper method for * implementing double dispatch */ public abstract IMoney addMoneyBag(MoneyBag s); /** * Tests whether this money is zero */ public abstract boolean isZero(); /** * Multiplies a money by the given factor. */ public abstract IMoney multiply(int factor); /** * Negates this money. */ public abstract IMoney negate(); /** * Subtracts a money from this money. */ public abstract IMoney subtract(IMoney m); /** * Append this to a MoneyBag m. * appendTo() needs to be public because it is used * polymorphically, but it should not be used by clients * because it modifies the argument m. */ public abstract void appendTo(MoneyBag m); }junit4-4.11/src/test/java/junit/samples/money/Money.java0000644000175000017500000000415212050524441022550 0ustar ebourgebourgpackage junit.samples.money; /** * A simple Money. */ public class Money implements IMoney { private int fAmount; private String fCurrency; /** * Constructs a money from the given amount and currency. */ public Money(int amount, String currency) { fAmount = amount; fCurrency = currency; } /** * Adds a money to this money. Forwards the request to the addMoney helper. */ public IMoney add(IMoney m) { return m.addMoney(this); } public IMoney addMoney(Money m) { if (m.currency().equals(currency())) { return new Money(amount() + m.amount(), currency()); } return MoneyBag.create(this, m); } public IMoney addMoneyBag(MoneyBag s) { return s.addMoney(this); } public int amount() { return fAmount; } public String currency() { return fCurrency; } @Override public boolean equals(Object anObject) { if (isZero()) { if (anObject instanceof IMoney) { return ((IMoney) anObject).isZero(); } } if (anObject instanceof Money) { Money aMoney = (Money) anObject; return aMoney.currency().equals(currency()) && amount() == aMoney.amount(); } return false; } @Override public int hashCode() { if (fAmount == 0) { return 0; } return fCurrency.hashCode() + fAmount; } public boolean isZero() { return amount() == 0; } public IMoney multiply(int factor) { return new Money(amount() * factor, currency()); } public IMoney negate() { return new Money(-amount(), currency()); } public IMoney subtract(IMoney m) { return add(m.negate()); } @Override public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("[" + amount() + " " + currency() + "]"); return buffer.toString(); } public /*this makes no sense*/ void appendTo(MoneyBag m) { m.appendMoney(this); } }junit4-4.11/src/test/java/junit/samples/money/MoneyBag.java0000644000175000017500000000755312050524441023172 0ustar ebourgebourgpackage junit.samples.money; import java.util.ArrayList; import java.util.List; /** * A MoneyBag defers exchange rate conversions. For example adding * 12 Swiss Francs to 14 US Dollars is represented as a bag * containing the two Monies 12 CHF and 14 USD. Adding another * 10 Swiss francs gives a bag with 22 CHF and 14 USD. Due to * the deferred exchange rate conversion we can later value a * MoneyBag with different exchange rates. * * A MoneyBag is represented as a list of Monies and provides * different constructors to create a MoneyBag. */ public class MoneyBag implements IMoney { private List fMonies = new ArrayList(5); public static IMoney create(IMoney m1, IMoney m2) { MoneyBag result = new MoneyBag(); m1.appendTo(result); m2.appendTo(result); return result.simplify(); } public IMoney add(IMoney m) { return m.addMoneyBag(this); } public IMoney addMoney(Money m) { return MoneyBag.create(m, this); } public IMoney addMoneyBag(MoneyBag s) { return MoneyBag.create(s, this); } void appendBag(MoneyBag aBag) { for (Money each : aBag.fMonies) { appendMoney(each); } } void appendMoney(Money aMoney) { if (aMoney.isZero()) return; IMoney old = findMoney(aMoney.currency()); if (old == null) { fMonies.add(aMoney); return; } fMonies.remove(old); Money sum = (Money) old.add(aMoney); if (sum.isZero()) { return; } fMonies.add(sum); } @Override public boolean equals(Object anObject) { if (isZero()) { if (anObject instanceof IMoney) { return ((IMoney) anObject).isZero(); } } if (anObject instanceof MoneyBag) { MoneyBag aMoneyBag = (MoneyBag) anObject; if (aMoneyBag.fMonies.size() != fMonies.size()) { return false; } for (Money each : fMonies) { if (!aMoneyBag.contains(each)) { return false; } } return true; } return false; } private Money findMoney(String currency) { for (Money each : fMonies) { if (each.currency().equals(currency)) { return each; } } return null; } private boolean contains(Money m) { Money found = findMoney(m.currency()); if (found == null) return false; return found.amount() == m.amount(); } @Override public int hashCode() { int hash = 0; for (Money each : fMonies) { hash ^= each.hashCode(); } return hash; } public boolean isZero() { return fMonies.size() == 0; } public IMoney multiply(int factor) { MoneyBag result = new MoneyBag(); if (factor != 0) { for (Money each : fMonies) { result.appendMoney((Money) each.multiply(factor)); } } return result; } public IMoney negate() { MoneyBag result = new MoneyBag(); for (Money each : fMonies) { result.appendMoney((Money) each.negate()); } return result; } private IMoney simplify() { if (fMonies.size() == 1) { return fMonies.iterator().next(); } return this; } public IMoney subtract(IMoney m) { return add(m.negate()); } @Override public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("{"); for (Money each : fMonies) { buffer.append(each); } buffer.append("}"); return buffer.toString(); } public void appendTo(MoneyBag m) { m.appendBag(this); } }junit4-4.11/src/test/java/junit/samples/money/MoneyTest.java0000644000175000017500000001270312050524441023411 0ustar ebourgebourgpackage junit.samples.money; import junit.framework.TestCase; public class MoneyTest extends TestCase { private Money f12CHF; private Money f14CHF; private Money f7USD; private Money f21USD; private IMoney fMB1; private IMoney fMB2; public static void main(String args[]) { junit.textui.TestRunner.run(MoneyTest.class); } @Override protected void setUp() { f12CHF = new Money(12, "CHF"); f14CHF = new Money(14, "CHF"); f7USD = new Money(7, "USD"); f21USD = new Money(21, "USD"); fMB1 = MoneyBag.create(f12CHF, f7USD); fMB2 = MoneyBag.create(f14CHF, f21USD); } public void testBagMultiply() { // {[12 CHF][7 USD]} *2 == {[24 CHF][14 USD]} IMoney expected = MoneyBag.create(new Money(24, "CHF"), new Money(14, "USD")); assertEquals(expected, fMB1.multiply(2)); assertEquals(fMB1, fMB1.multiply(1)); assertTrue(fMB1.multiply(0).isZero()); } public void testBagNegate() { // {[12 CHF][7 USD]} negate == {[-12 CHF][-7 USD]} IMoney expected = MoneyBag.create(new Money(-12, "CHF"), new Money(-7, "USD")); assertEquals(expected, fMB1.negate()); } public void testBagSimpleAdd() { // {[12 CHF][7 USD]} + [14 CHF] == {[26 CHF][7 USD]} IMoney expected = MoneyBag.create(new Money(26, "CHF"), new Money(7, "USD")); assertEquals(expected, fMB1.add(f14CHF)); } public void testBagSubtract() { // {[12 CHF][7 USD]} - {[14 CHF][21 USD] == {[-2 CHF][-14 USD]} IMoney expected = MoneyBag.create(new Money(-2, "CHF"), new Money(-14, "USD")); assertEquals(expected, fMB1.subtract(fMB2)); } public void testBagSumAdd() { // {[12 CHF][7 USD]} + {[14 CHF][21 USD]} == {[26 CHF][28 USD]} IMoney expected = MoneyBag.create(new Money(26, "CHF"), new Money(28, "USD")); assertEquals(expected, fMB1.add(fMB2)); } public void testIsZero() { assertTrue(fMB1.subtract(fMB1).isZero()); assertTrue(MoneyBag.create(new Money(0, "CHF"), new Money(0, "USD")).isZero()); } public void testMixedSimpleAdd() { // [12 CHF] + [7 USD] == {[12 CHF][7 USD]} IMoney expected = MoneyBag.create(f12CHF, f7USD); assertEquals(expected, f12CHF.add(f7USD)); } public void testBagNotEquals() { IMoney bag = MoneyBag.create(f12CHF, f7USD); assertFalse(bag.equals(new Money(12, "DEM").add(f7USD))); } public void testMoneyBagEquals() { assertTrue(!fMB1.equals(null)); assertEquals(fMB1, fMB1); IMoney equal = MoneyBag.create(new Money(12, "CHF"), new Money(7, "USD")); assertTrue(fMB1.equals(equal)); assertTrue(!fMB1.equals(f12CHF)); assertTrue(!f12CHF.equals(fMB1)); assertTrue(!fMB1.equals(fMB2)); } public void testMoneyBagHash() { IMoney equal = MoneyBag.create(new Money(12, "CHF"), new Money(7, "USD")); assertEquals(fMB1.hashCode(), equal.hashCode()); } public void testMoneyEquals() { assertTrue(!f12CHF.equals(null)); Money equalMoney = new Money(12, "CHF"); assertEquals(f12CHF, f12CHF); assertEquals(f12CHF, equalMoney); assertEquals(f12CHF.hashCode(), equalMoney.hashCode()); assertTrue(!f12CHF.equals(f14CHF)); } public void testMoneyHash() { assertTrue(!f12CHF.equals(null)); Money equal = new Money(12, "CHF"); assertEquals(f12CHF.hashCode(), equal.hashCode()); } public void testSimplify() { IMoney money = MoneyBag.create(new Money(26, "CHF"), new Money(28, "CHF")); assertEquals(new Money(54, "CHF"), money); } public void testNormalize2() { // {[12 CHF][7 USD]} - [12 CHF] == [7 USD] Money expected = new Money(7, "USD"); assertEquals(expected, fMB1.subtract(f12CHF)); } public void testNormalize3() { // {[12 CHF][7 USD]} - {[12 CHF][3 USD]} == [4 USD] IMoney ms1 = MoneyBag.create(new Money(12, "CHF"), new Money(3, "USD")); Money expected = new Money(4, "USD"); assertEquals(expected, fMB1.subtract(ms1)); } public void testNormalize4() { // [12 CHF] - {[12 CHF][3 USD]} == [-3 USD] IMoney ms1 = MoneyBag.create(new Money(12, "CHF"), new Money(3, "USD")); Money expected = new Money(-3, "USD"); assertEquals(expected, f12CHF.subtract(ms1)); } public void testPrint() { assertEquals("[12 CHF]", f12CHF.toString()); } public void testSimpleAdd() { // [12 CHF] + [14 CHF] == [26 CHF] Money expected = new Money(26, "CHF"); assertEquals(expected, f12CHF.add(f14CHF)); } public void testSimpleBagAdd() { // [14 CHF] + {[12 CHF][7 USD]} == {[26 CHF][7 USD]} IMoney expected = MoneyBag.create(new Money(26, "CHF"), new Money(7, "USD")); assertEquals(expected, f14CHF.add(fMB1)); } public void testSimpleMultiply() { // [14 CHF] *2 == [28 CHF] Money expected = new Money(28, "CHF"); assertEquals(expected, f14CHF.multiply(2)); } public void testSimpleNegate() { // [14 CHF] negate == [-14 CHF] Money expected = new Money(-14, "CHF"); assertEquals(expected, f14CHF.negate()); } public void testSimpleSubtract() { // [14 CHF] - [12 CHF] == [2 CHF] Money expected = new Money(2, "CHF"); assertEquals(expected, f14CHF.subtract(f12CHF)); } }junit4-4.11/src/test/java/junit/samples/ListTest.java0000644000175000017500000000320012050524441022076 0ustar ebourgebourgpackage junit.samples; import java.util.ArrayList; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * A sample test case, testing {@link java.util.Vector}. */ public class ListTest extends TestCase { protected List fEmpty; protected List fFull; public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } @Override protected void setUp() { fEmpty = new ArrayList(); fFull = new ArrayList(); fFull.add(1); fFull.add(2); fFull.add(3); } public static Test suite() { return new TestSuite(ListTest.class); } public void testCapacity() { int size = fFull.size(); for (int i = 0; i < 100; i++) { fFull.add(new Integer(i)); } assertTrue(fFull.size() == 100 + size); } public void testContains() { assertTrue(fFull.contains(1)); assertTrue(!fEmpty.contains(1)); } public void testElementAt() { int i = fFull.get(0); assertTrue(i == 1); try { fFull.get(fFull.size()); } catch (IndexOutOfBoundsException e) { return; } fail("Should raise an ArrayIndexOutOfBoundsException"); } public void testRemoveAll() { fFull.removeAll(fFull); fEmpty.removeAll(fEmpty); assertTrue(fFull.isEmpty()); assertTrue(fEmpty.isEmpty()); } public void testRemoveElement() { fFull.remove(new Integer(3)); assertTrue(!fFull.contains(3)); } }junit4-4.11/src/test/java/junit/samples/SimpleTest.java0000644000175000017500000000312212050524441022417 0ustar ebourgebourgpackage junit.samples; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Some simple tests. */ public class SimpleTest extends TestCase { protected int fValue1; protected int fValue2; @Override protected void setUp() { fValue1 = 2; fValue2 = 3; } public static Test suite() { /* * the type safe way * TestSuite suite= new TestSuite(); suite.addTest( new SimpleTest("add") { protected void runTest() { testAdd(); } } ); suite.addTest( new SimpleTest("testDivideByZero") { protected void runTest() { testDivideByZero(); } } ); return suite; */ /* * the dynamic way */ return new TestSuite(SimpleTest.class); } public void testAdd() { double result = fValue1 + fValue2; // forced failure result == 5 assertTrue(result == 6); } public int unused; public void testDivideByZero() { int zero = 0; int result = 8 / zero; unused = result; // avoid warning for not using result } public void testEquals() { assertEquals(12, 12); assertEquals(12L, 12L); assertEquals(new Long(12), new Long(12)); assertEquals("Size", 12, 13); assertEquals("Capacity", 12.0, 11.99, 0.0); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } }junit4-4.11/src/test/java/junit/samples/AllTests.java0000644000175000017500000000105212050524441022061 0ustar ebourgebourgpackage junit.samples; import junit.framework.Test; import junit.framework.TestSuite; /** * TestSuite that runs all the sample tests */ public class AllTests { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { TestSuite suite = new TestSuite("All JUnit Tests"); suite.addTest(ListTest.suite()); suite.addTest(new TestSuite(junit.samples.money.MoneyTest.class)); suite.addTest(junit.tests.AllTests.suite()); return suite; } }junit4-4.11/src/test/java/org/0000755000175000017500000000000012050524441015457 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/0000755000175000017500000000000012050524441016610 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/0000755000175000017500000000000012050524441017752 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/package-info.java0000644000175000017500000000022312050524441023136 0ustar ebourgebourg/** * Tests the JUnit functionality. * * Corresponds to {@link junit.tests.AllTests} in Junit 3.x. * * @since 4.0 */ package org.junit.tests;junit4-4.11/src/test/java/org/junit/tests/TestSystem.java0000644000175000017500000000105312050524441022740 0ustar ebourgebourgpackage org.junit.tests; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.io.PrintStream; import org.junit.internal.JUnitSystem; public class TestSystem implements JUnitSystem { private PrintStream out; private ByteArrayOutputStream fOutContents; public TestSystem() { fOutContents = new ByteArrayOutputStream(); out = new PrintStream(fOutContents); } public PrintStream out() { return out; } public OutputStream outContents() { return fOutContents; } } junit4-4.11/src/test/java/org/junit/tests/deprecated/0000755000175000017500000000000012050524441022052 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/deprecated/JUnit4ClassRunnerTest.java0000644000175000017500000000324112050524441027052 0ustar ebourgebourgpackage org.junit.tests.deprecated; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import org.junit.Test; import org.junit.internal.runners.JUnit4ClassRunner; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.RunWith; /** * @deprecated This is a simple smoke test to make sure the old JUnit4ClassRunner basically works. * Delete this test when JUnit4ClassRunner goes to the Great Heap In The Sky. */ @Deprecated public class JUnit4ClassRunnerTest { @SuppressWarnings("deprecation") @RunWith(JUnit4ClassRunner.class) public static class Example { @Test public void success() { } @Test public void failure() { fail(); } } @Test public void runWithOldJUnit4ClassRunner() { Result result = JUnitCore.runClasses(Example.class); assertThat(result.getRunCount(), is(2)); assertThat(result.getFailureCount(), is(1)); } @SuppressWarnings("deprecation") @RunWith(JUnit4ClassRunner.class) public static class UnconstructableExample { public UnconstructableExample() { throw new UnsupportedOperationException(); } @Test public void success() { } @Test public void failure() { fail(); } } @Test public void runWithOldJUnit4ClassRunnerAndBadConstructor() { Result result = JUnitCore.runClasses(UnconstructableExample.class); assertThat(result.getRunCount(), is(2)); assertThat(result.getFailureCount(), is(2)); } } junit4-4.11/src/test/java/org/junit/tests/experimental/0000755000175000017500000000000012050524441022447 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/experimental/AssumptionViolatedExceptionTest.java0000644000175000017500000000347712050524441031676 0ustar ebourgebourgpackage org.junit.tests.experimental; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import static org.junit.Assume.assumeThat; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; import org.junit.Test; import org.junit.experimental.theories.DataPoint; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.internal.AssumptionViolatedException; import org.junit.runner.RunWith; @RunWith(Theories.class) public class AssumptionViolatedExceptionTest { @DataPoint public static Object TWO = 2; @DataPoint public static Matcher IS_THREE = is(3); @DataPoint public static Matcher NULL = null; @Theory public void toStringReportsMatcher(Object actual, Matcher matcher) { assumeThat(matcher, notNullValue()); assertThat(new AssumptionViolatedException(actual, matcher).toString(), containsString(matcher.toString())); } @Theory public void toStringReportsValue(Object actual, Matcher matcher) { assertThat(new AssumptionViolatedException(actual, matcher).toString(), containsString(String.valueOf(actual))); } @Test public void AssumptionViolatedExceptionDescribesItself() { AssumptionViolatedException e = new AssumptionViolatedException(3, is(2)); assertThat(StringDescription.asString(e), is("got: <3>, expected: is <2>")); } @Test public void simpleAssumptionViolatedExceptionDescribesItself() { AssumptionViolatedException e = new AssumptionViolatedException("not enough money"); assertThat(StringDescription.asString(e), is("not enough money")); } } junit4-4.11/src/test/java/org/junit/tests/experimental/max/0000755000175000017500000000000012050524441023234 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/experimental/max/JUnit38SortingTest.java0000644000175000017500000000266612050524441027523 0ustar ebourgebourgpackage org.junit.tests.experimental.max; import static org.junit.Assert.assertEquals; import java.io.File; import java.util.List; import junit.framework.TestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.max.MaxCore; import org.junit.runner.Description; import org.junit.runner.Request; public class JUnit38SortingTest { private MaxCore fMax; private File fMaxFile; @Before public void createMax() { fMaxFile = new File("MaxCore.ser"); if (fMaxFile.exists()) { fMaxFile.delete(); } fMax = MaxCore.storedLocally(fMaxFile); } @After public void forgetMax() { fMaxFile.delete(); } public static class JUnit4Test { @Test public void pass() { } } public static class JUnit38Test extends TestCase { public void testFails() { fail(); } public void testSucceeds() { } public void testSucceedsToo() { } } @Test public void preferRecentlyFailed38Test() { Request request = Request.classes(JUnit4Test.class, JUnit38Test.class); fMax.run(request); List tests = fMax.sortedLeavesForTest(request); Description dontSucceed = Description.createTestDescription( JUnit38Test.class, "testFails"); assertEquals(dontSucceed, tests.get(0)); } } junit4-4.11/src/test/java/org/junit/tests/experimental/max/DescriptionTest.java0000644000175000017500000001115212050524441027222 0ustar ebourgebourgpackage org.junit.tests.experimental.max; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import java.lang.annotation.Annotation; import java.net.URL; import java.net.URLClassLoader; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.Description; public class DescriptionTest { @Test public void parseClass_whenCantParse() { assertNull(Description.TEST_MECHANISM.getTestClass()); } @Test public void parseMethod_whenCantParse() { assertNull(Description.TEST_MECHANISM.getMethodName()); } @Test(expected = IllegalArgumentException.class) public void createSuiteDescription_whenZeroLength() { Description.createSuiteDescription(""); } @Test(expected = IllegalArgumentException.class) public void createSuiteDescription_whenNull() { Description.createSuiteDescription((String) null); } @Test public void parseClassAndMethodNoAnnotations() throws Exception { Description description = Description.createTestDescription(Description.class, "aTestMethod"); assertThat(description.getClassName(), equalTo("org.junit.runner.Description")); assertThat(description.getMethodName(), equalTo("aTestMethod")); assertThat(description.getAnnotations().size(), equalTo(0)); } @Test public void parseClassAndMethodWithAnnotations() throws Exception { Annotation[] annotations = DescriptionTest.class.getMethod("parseClassAndMethodWithAnnotations").getDeclaredAnnotations(); Description description = Description.createTestDescription(Description.class, "aTestMethod", annotations); assertThat(description.getClassName(), equalTo("org.junit.runner.Description")); assertThat(description.getMethodName(), equalTo("aTestMethod")); assertThat(description.getAnnotations().size(), equalTo(1)); } @Test public void parseClassNameAndMethodUniqueId() throws Exception { Description description = Description.createTestDescription("not a class name", "aTestMethod", 123); assertThat(description.getClassName(), equalTo("not a class name")); assertThat(description.getMethodName(), equalTo("aTestMethod")); assertThat(description.getAnnotations().size(), equalTo(0)); } @Test public void sameNamesButDifferentUniqueIdAreNotEqual() throws Exception { assertThat(Description.createTestDescription("not a class name", "aTestMethod", 1), not(equalTo(Description.createTestDescription("not a class name", "aTestMethod", 2)))); } @Test public void usesPassedInClassObject() throws Exception { class URLClassLoader2 extends URLClassLoader { URLClassLoader2(URL... urls) { super(urls); } @Override // just making public public Class findClass(String name) throws ClassNotFoundException { return super.findClass(name); } } URL classpath = Sweet.class.getProtectionDomain().getCodeSource().getLocation(); URLClassLoader2 loader = new URLClassLoader2(classpath); Class clazz = loader.findClass(Sweet.class.getName()); assertEquals(loader, clazz.getClassLoader()); Description d = Description.createSuiteDescription(clazz); assertEquals(clazz, d.getTestClass()); assertNull(d.getMethodName()); assertEquals(1, d.getAnnotations().size()); assertEquals(Ignore.class, d.getAnnotations().iterator().next().annotationType()); d = Description.createTestDescription(clazz, "tessed"); assertEquals(clazz, d.getTestClass()); assertEquals("tessed", d.getMethodName()); assertEquals(0, d.getAnnotations().size()); d = Description.createTestDescription(clazz, "tessed", clazz.getMethod("tessed").getAnnotations()); assertEquals(clazz, d.getTestClass()); assertEquals("tessed", d.getMethodName()); assertEquals(1, d.getAnnotations().size()); assertEquals(Test.class, d.getAnnotations().iterator().next().annotationType()); d = d.childlessCopy(); assertEquals(clazz, d.getTestClass()); assertEquals("tessed", d.getMethodName()); assertEquals(1, d.getAnnotations().size()); assertEquals(Test.class, d.getAnnotations().iterator().next().annotationType()); } @Ignore private static class Sweet { @Test public void tessed() { } } } junit4-4.11/src/test/java/org/junit/tests/experimental/max/MaxStarterTest.java0000644000175000017500000002267412050524441027044 0ustar ebourgebourgpackage org.junit.tests.experimental.max; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.max.MaxCore; import org.junit.internal.runners.JUnit38ClassRunner; import org.junit.runner.Computer; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.Request; import org.junit.runner.Result; import org.junit.runner.Runner; import org.junit.runner.manipulation.Filter; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; import org.junit.tests.AllTests; public class MaxStarterTest { private MaxCore fMax; private File fMaxFile; @Before public void createMax() { fMaxFile = new File("MaxCore.ser"); if (fMaxFile.exists()) { fMaxFile.delete(); } fMax = MaxCore.storedLocally(fMaxFile); } @After public void forgetMax() { fMaxFile.delete(); } public static class TwoTests { @Test public void succeed() { } @Test public void dontSucceed() { fail(); } } @Test public void twoTestsNotRunComeBackInRandomOrder() { Request request = Request.aClass(TwoTests.class); List things = fMax.sortedLeavesForTest(request); Description succeed = Description.createTestDescription(TwoTests.class, "succeed"); Description dontSucceed = Description.createTestDescription( TwoTests.class, "dontSucceed"); assertTrue(things.contains(succeed)); assertTrue(things.contains(dontSucceed)); assertEquals(2, things.size()); } @Test public void preferNewTests() { Request one = Request.method(TwoTests.class, "succeed"); fMax.run(one); Request two = Request.aClass(TwoTests.class); List things = fMax.sortedLeavesForTest(two); Description dontSucceed = Description.createTestDescription( TwoTests.class, "dontSucceed"); assertEquals(dontSucceed, things.get(0)); assertEquals(2, things.size()); } // This covers a seemingly-unlikely case, where you had a test that failed // on the // last run and you also introduced new tests. In such a case it pretty much // doesn't matter // which order they run, you just want them both to be early in the sequence @Test public void preferNewTestsOverTestsThatFailed() { Request one = Request.method(TwoTests.class, "dontSucceed"); fMax.run(one); Request two = Request.aClass(TwoTests.class); List things = fMax.sortedLeavesForTest(two); Description succeed = Description.createTestDescription(TwoTests.class, "succeed"); assertEquals(succeed, things.get(0)); assertEquals(2, things.size()); } @Test public void preferRecentlyFailed() { Request request = Request.aClass(TwoTests.class); fMax.run(request); List tests = fMax.sortedLeavesForTest(request); Description dontSucceed = Description.createTestDescription( TwoTests.class, "dontSucceed"); assertEquals(dontSucceed, tests.get(0)); } @Test public void sortTestsInMultipleClasses() { Request request = Request.classes(Computer.serial(), TwoTests.class, TwoTests.class); fMax.run(request); List tests = fMax.sortedLeavesForTest(request); Description dontSucceed = Description.createTestDescription( TwoTests.class, "dontSucceed"); assertEquals(dontSucceed, tests.get(0)); assertEquals(dontSucceed, tests.get(1)); } public static class TwoUnEqualTests { @Test public void slow() throws InterruptedException { Thread.sleep(100); fail(); } @Test public void fast() { fail(); } } @Test public void rememberOldRuns() { fMax.run(TwoUnEqualTests.class); MaxCore reincarnation = MaxCore.storedLocally(fMaxFile); List failures = reincarnation.run(TwoUnEqualTests.class) .getFailures(); assertEquals("fast", failures.get(0).getDescription().getMethodName()); assertEquals("slow", failures.get(1).getDescription().getMethodName()); } @Test public void preferFast() { Request request = Request.aClass(TwoUnEqualTests.class); fMax.run(request); Description thing = fMax.sortedLeavesForTest(request).get(1); assertEquals(Description.createTestDescription(TwoUnEqualTests.class, "slow"), thing); } @Test public void listenersAreCalledCorrectlyInTheFaceOfFailures() throws Exception { JUnitCore core = new JUnitCore(); final List failures = new ArrayList(); core.addListener(new RunListener() { @Override public void testRunFinished(Result result) throws Exception { failures.addAll(result.getFailures()); } }); fMax.run(Request.aClass(TwoTests.class), core); assertEquals(1, failures.size()); } @Test public void testsAreOnlyIncludedOnceWhenExpandingForSorting() throws Exception { Result result = fMax.run(Request.aClass(TwoTests.class)); assertEquals(2, result.getRunCount()); } public static class TwoOldTests extends TestCase { public void testOne() { } public void testTwo() { } } @Test public void junit3TestsAreRunOnce() throws Exception { Result result = fMax.run(Request.aClass(TwoOldTests.class), new JUnitCore()); assertEquals(2, result.getRunCount()); } @Test public void filterSingleMethodFromOldTestClass() throws Exception { final Description method = Description.createTestDescription( TwoOldTests.class, "testOne"); Filter filter = Filter.matchMethodDescription(method); JUnit38ClassRunner child = new JUnit38ClassRunner(TwoOldTests.class); child.filter(filter); assertEquals(1, child.testCount()); } @Test public void testCountsStandUpToFiltration() { assertFilterLeavesTestUnscathed(AllTests.class); } private void assertFilterLeavesTestUnscathed(Class testClass) { Request oneClass = Request.aClass(testClass); Request filtered = oneClass.filterWith(new Filter() { @Override public boolean shouldRun(Description description) { return true; } @Override public String describe() { return "Everything"; } }); int filterCount = filtered.getRunner().testCount(); int coreCount = oneClass.getRunner().testCount(); assertEquals("Counts match up in " + testClass, coreCount, filterCount); } private static class MalformedJUnit38Test { private MalformedJUnit38Test() { } @SuppressWarnings("unused") public void testSucceeds() { } } @Test public void maxShouldSkipMalformedJUnit38Classes() { Request request = Request.aClass(MalformedJUnit38Test.class); fMax.run(request); } public static class MalformedJUnit38TestMethod extends TestCase { @SuppressWarnings("unused") private void testNothing() { } } String fMessage = null; @Test public void correctErrorFromMalformedTest() { Request request = Request.aClass(MalformedJUnit38TestMethod.class); JUnitCore core = new JUnitCore(); Request sorted = fMax.sortRequest(request); Runner runner = sorted.getRunner(); Result result = core.run(runner); Failure failure = result.getFailures().get(0); assertThat(failure.toString(), containsString("MalformedJUnit38TestMethod")); assertThat(failure.toString(), containsString("testNothing")); assertThat(failure.toString(), containsString("isn't public")); } public static class HalfMalformedJUnit38TestMethod extends TestCase { public void testSomething() { } @SuppressWarnings("unused") private void testNothing() { } } @Test public void halfMalformed() { assertThat(JUnitCore.runClasses(HalfMalformedJUnit38TestMethod.class) .getFailureCount(), is(1)); } @Test public void correctErrorFromHalfMalformedTest() { Request request = Request.aClass(HalfMalformedJUnit38TestMethod.class); JUnitCore core = new JUnitCore(); Request sorted = fMax.sortRequest(request); Runner runner = sorted.getRunner(); Result result = core.run(runner); Failure failure = result.getFailures().get(0); assertThat(failure.toString(), containsString("MalformedJUnit38TestMethod")); assertThat(failure.toString(), containsString("testNothing")); assertThat(failure.toString(), containsString("isn't public")); } } junit4-4.11/src/test/java/org/junit/tests/experimental/results/0000755000175000017500000000000012050524441024150 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/experimental/results/PrintableResultTest.java0000644000175000017500000000370412050524441030776 0ustar ebourgebourgpackage org.junit.tests.experimental.results; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertThat; import java.util.Arrays; import org.junit.experimental.results.PrintableResult; import org.junit.experimental.theories.DataPoint; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.Description; import org.junit.runner.RunWith; import org.junit.runner.notification.Failure; @RunWith(Theories.class) public class PrintableResultTest { @Theory(nullsAccepted = false) public void backTraceHasGoodToString(String descriptionName, final String stackTraceClassName) { Failure failure = new Failure(Description .createSuiteDescription(descriptionName), new Throwable() { private static final long serialVersionUID = 1L; @Override public StackTraceElement[] getStackTrace() { return new StackTraceElement[]{new StackTraceElement( stackTraceClassName, "methodName", "fileName", 1)}; } }); assertThat(new PrintableResult(asList(failure)).toString(), allOf( containsString(descriptionName), containsString(stackTraceClassName))); } @DataPoint public static String SHELL_POINT = "Shell Point"; @Theory public void includeMultipleFailures(String secondExceptionName) { PrintableResult backtrace = new PrintableResult(Arrays.asList( new Failure(Description.createSuiteDescription("firstName"), new RuntimeException("firstException")), new Failure( Description.createSuiteDescription("secondName"), new RuntimeException(secondExceptionName)))); assertThat(backtrace.toString(), containsString(secondExceptionName)); } } junit4-4.11/src/test/java/org/junit/tests/experimental/results/ResultMatchersTest.java0000644000175000017500000000130212050524441030614 0ustar ebourgebourgpackage org.junit.tests.experimental.results; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import org.junit.Test; import org.junit.experimental.results.ResultMatchers; import org.junit.experimental.theories.Theory; public class ResultMatchersTest { @Test public void hasFailuresHasGoodDescription() { assertThat(ResultMatchers.failureCountIs(3).toString(), is("has 3 failures")); } @Theory public void hasFailuresDescriptionReflectsInput(int i) { assertThat(ResultMatchers.failureCountIs(i).toString(), containsString("" + i)); } } junit4-4.11/src/test/java/org/junit/tests/experimental/rules/0000755000175000017500000000000012050524441023601 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/experimental/rules/BlockJUnit4ClassRunnerOverrideTest.java0000644000175000017500000000574612050524441033270 0ustar ebourgebourgpackage org.junit.tests.experimental.rules; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.experimental.results.PrintableResult.testResult; import static org.junit.experimental.results.ResultMatchers.isSuccessful; import java.util.LinkedList; import java.util.List; import org.junit.Test; import org.junit.rules.MethodRule; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runner.RunWith; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement; @SuppressWarnings("deprecation") public class BlockJUnit4ClassRunnerOverrideTest { public static class FlipBitRule implements MethodRule { public Statement apply(final Statement base, FrameworkMethod method, final Object target) { return new Statement() { @Override public void evaluate() throws Throwable { target.getClass().getField("flipBit").set(target, true); base.evaluate(); } }; } } public static class OverrideRulesRunner extends BlockJUnit4ClassRunner { public OverrideRulesRunner(Class klass) throws InitializationError { super(klass); } @Override protected List rules(Object test) { final LinkedList methodRules = new LinkedList( super.rules(test)); methodRules.add(new FlipBitRule()); return methodRules; } } @RunWith(OverrideRulesRunner.class) public static class OverrideRulesTest { public boolean flipBit = false; @Test public void testFlipBit() { assertTrue(flipBit); } } @Test public void overrideRulesMethod() { assertThat(testResult(OverrideTestRulesTest.class), isSuccessful()); } public static class OverrideTestRulesRunner extends BlockJUnit4ClassRunner { public OverrideTestRulesRunner(Class klass) throws InitializationError { super(klass); } @Override protected List getTestRules(final Object test) { final LinkedList methodRules = new LinkedList( super.getTestRules(test)); methodRules.add(new TestRule() { public Statement apply(Statement base, Description description) { return new FlipBitRule().apply(base, null, test); } }); return methodRules; } } @RunWith(OverrideTestRulesRunner.class) public static class OverrideTestRulesTest extends OverrideRulesTest { } @Test public void overrideTestRulesMethod() { assertThat(testResult(OverrideRulesTest.class), isSuccessful()); } } junit4-4.11/src/test/java/org/junit/tests/experimental/rules/VerifierRuleTest.java0000644000175000017500000001121712050524441027711 0ustar ebourgebourgpackage org.junit.tests.experimental.rules; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.experimental.results.PrintableResult.testResult; import static org.junit.experimental.results.ResultMatchers.hasFailureContaining; import static org.junit.experimental.results.ResultMatchers.isSuccessful; import java.util.concurrent.Callable; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.results.PrintableResult; import org.junit.rules.ErrorCollector; import org.junit.rules.Verifier; public class VerifierRuleTest { public static class UsesErrorCollector { @Rule public ErrorCollector collector = new ErrorCollector(); @Test public void example() { collector.addError(new Throwable("message")); } } @Test public void usedErrorCollectorShouldFail() { assertThat(testResult(UsesErrorCollector.class), hasFailureContaining("message")); } public static class UsesErrorCollectorTwice { @Rule public ErrorCollector collector = new ErrorCollector(); @Test public void example() { collector.addError(new Throwable("first thing went wrong")); collector.addError(new Throwable("second thing went wrong")); } } @Test public void usedErrorCollectorTwiceShouldFail() { PrintableResult testResult = testResult(UsesErrorCollectorTwice.class); assertThat(testResult, hasFailureContaining("first thing went wrong")); assertThat(testResult, hasFailureContaining("second thing went wrong")); } public static class UsesErrorCollectorCheckThat { @Rule public ErrorCollector collector = new ErrorCollector(); @Test public void example() { collector.checkThat(3, is(4)); collector.checkThat(5, is(6)); collector.checkThat("reason 1", 7, is(8)); collector.checkThat("reason 2", 9, is(16)); } } @Test public void usedErrorCollectorCheckThatShouldFail() { PrintableResult testResult = testResult(UsesErrorCollectorCheckThat.class); assertThat(testResult, hasFailureContaining("was <3>")); assertThat(testResult, hasFailureContaining("was <5>")); assertThat(testResult, hasFailureContaining("reason 1")); assertThat(testResult, hasFailureContaining("was <7>")); assertThat(testResult, hasFailureContaining("reason 2")); assertThat(testResult, hasFailureContaining("was <9>")); } public static class UsesErrorCollectorCheckSucceeds { @Rule public ErrorCollector collector = new ErrorCollector(); @Test public void example() { collector.checkSucceeds(new Callable() { public Object call() throws Exception { throw new RuntimeException("first!"); } }); collector.checkSucceeds(new Callable() { public Object call() throws Exception { throw new RuntimeException("second!"); } }); } } @Test public void usedErrorCollectorCheckSucceedsShouldFail() { PrintableResult testResult = testResult(UsesErrorCollectorCheckSucceeds.class); assertThat(testResult, hasFailureContaining("first!")); assertThat(testResult, hasFailureContaining("second!")); } public static class UsesErrorCollectorCheckSucceedsPasses { @Rule public ErrorCollector collector = new ErrorCollector(); @Test public void example() { assertEquals(3, collector.checkSucceeds(new Callable() { public Object call() throws Exception { return 3; } })); } } @Test public void usedErrorCollectorCheckSucceedsShouldPass() { PrintableResult testResult = testResult(UsesErrorCollectorCheckSucceedsPasses.class); assertThat(testResult, isSuccessful()); } private static String sequence; public static class UsesVerifier { @Rule public Verifier collector = new Verifier() { @Override protected void verify() { sequence += "verify "; } }; @Test public void example() { sequence += "test "; } } @Test public void verifierRunsAfterTest() { sequence = ""; assertThat(testResult(UsesVerifier.class), isSuccessful()); assertEquals("test verify ", sequence); } }junit4-4.11/src/test/java/org/junit/tests/experimental/rules/ClassRulesTest.java0000644000175000017500000001622712050524441027374 0ustar ebourgebourg/** * Created Oct 19, 2009 */ package org.junit.tests.experimental.rules; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.experimental.results.PrintableResult.testResult; import static org.junit.experimental.results.ResultMatchers.isSuccessful; import java.util.LinkedList; import java.util.List; import org.junit.ClassRule; import org.junit.Test; import org.junit.rules.ExternalResource; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runners.model.Statement; /** * Tests to exercise class-level rules. * This test class is very similar to {@link ClassRulesMethodTest}. If you add a test here, then it is likely that the other will have to be changed. * This tests {@link ClassRule}s attached to fields. * {@link ClassRulesMethodTest} tests {@link ClassRule}s attached to methods. */ public class ClassRulesTest { public static class Counter extends ExternalResource { public int count = 0; @Override protected void before() throws Throwable { count++; } } public static class ExampleTestWithClassRule { @ClassRule public static Counter counter = new Counter(); @Test public void firstTest() { assertEquals(1, counter.count); } @Test public void secondTest() { assertEquals(1, counter.count); } } @Test public void ruleIsAppliedOnce() { ExampleTestWithClassRule.counter.count = 0; JUnitCore.runClasses(ExampleTestWithClassRule.class); assertEquals(1, ExampleTestWithClassRule.counter.count); } public static class SubclassOfTestWithClassRule extends ExampleTestWithClassRule { } @Test public void ruleIsIntroducedAndEvaluatedOnSubclass() { ExampleTestWithClassRule.counter.count = 0; JUnitCore.runClasses(SubclassOfTestWithClassRule.class); assertEquals(1, ExampleTestWithClassRule.counter.count); } public static class CustomCounter implements TestRule { public int count = 0; public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { count++; base.evaluate(); } }; } } public static class ExampleTestWithCustomClassRule { @ClassRule public static CustomCounter counter = new CustomCounter(); @Test public void firstTest() { assertEquals(1, counter.count); } @Test public void secondTest() { assertEquals(1, counter.count); } } @Test public void customRuleIsAppliedOnce() { ExampleTestWithCustomClassRule.counter.count = 0; Result result = JUnitCore.runClasses(ExampleTestWithCustomClassRule.class); assertTrue(result.wasSuccessful()); assertEquals(1, ExampleTestWithCustomClassRule.counter.count); } private static final List orderList = new LinkedList(); private static class OrderTestRule implements TestRule { private String name; public OrderTestRule(String name) { this.name = name; } public Statement apply(final Statement base, final Description description) { return new Statement() { @Override public void evaluate() throws Throwable { orderList.add(name); base.evaluate(); } }; } } ; public static class UsesFieldAndMethodRule { @ClassRule public static OrderTestRule orderMethod() { return new OrderTestRule("orderMethod"); } @ClassRule public static OrderTestRule orderField = new OrderTestRule("orderField"); @Test public void foo() { assertEquals("orderField", orderList.get(0)); assertEquals("orderMethod", orderList.get(1)); } } @Test public void usesFieldAndMethodRule() { orderList.clear(); assertThat(testResult(UsesFieldAndMethodRule.class), isSuccessful()); } public static class MethodExampleTestWithClassRule { private static Counter counter = new Counter(); @ClassRule public static Counter getCounter() { return counter; } @Test public void firstTest() { assertEquals(1, counter.count); } @Test public void secondTest() { assertEquals(1, counter.count); } } @Test public void methodRuleIsAppliedOnce() { MethodExampleTestWithClassRule.counter.count = 0; JUnitCore.runClasses(MethodExampleTestWithClassRule.class); assertEquals(1, MethodExampleTestWithClassRule.counter.count); } public static class MethodSubclassOfTestWithClassRule extends MethodExampleTestWithClassRule { } @Test public void methodRuleIsIntroducedAndEvaluatedOnSubclass() { MethodExampleTestWithClassRule.counter.count = 0; JUnitCore.runClasses(MethodSubclassOfTestWithClassRule.class); assertEquals(1, MethodExampleTestWithClassRule.counter.count); } public static class MethodExampleTestWithCustomClassRule { private static CustomCounter counter = new CustomCounter(); @ClassRule public static CustomCounter getCounter() { return counter; } @Test public void firstTest() { assertEquals(1, counter.count); } @Test public void secondTest() { assertEquals(1, counter.count); } } @Test public void methodCustomRuleIsAppliedOnce() { MethodExampleTestWithCustomClassRule.counter.count = 0; Result result = JUnitCore.runClasses(MethodExampleTestWithCustomClassRule.class); assertTrue(result.wasSuccessful()); assertEquals(1, MethodExampleTestWithCustomClassRule.counter.count); } public static class CallMethodOnlyOnceRule { static int countOfMethodCalls = 0; private static class Dummy implements TestRule { public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { base.evaluate(); } ; }; } } @ClassRule public static Dummy both() { countOfMethodCalls++; return new Dummy(); } @Test public void onlyOnce() { assertEquals(1, countOfMethodCalls); } } @Test public void testCallMethodOnlyOnceRule() { CallMethodOnlyOnceRule.countOfMethodCalls = 0; assertTrue(JUnitCore.runClasses(CallMethodOnlyOnceRule.class).wasSuccessful()); } } junit4-4.11/src/test/java/org/junit/tests/experimental/rules/TestRuleTest.java0000644000175000017500000004754612050524441027073 0ustar ebourgebourgpackage org.junit.tests.experimental.rules; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.experimental.results.PrintableResult.testResult; import static org.junit.experimental.results.ResultMatchers.hasSingleFailureContaining; import static org.junit.experimental.results.ResultMatchers.isSuccessful; import java.util.LinkedList; import java.util.List; import org.junit.After; import org.junit.Assume; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.internal.AssumptionViolatedException; import org.junit.rules.TestName; import org.junit.rules.TestRule; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; /** * This test class is very similar to {@link TestMethodRuleTest}. If you add a test here, then it is likely that the other will have to be changed. * This tests {@link Rule}s attached to fields. * {@link TestMethodRuleTest} tests {@link Rule}s attached to methods. */ public class TestRuleTest { private static boolean wasRun; public static class ExampleTest { @Rule public TestRule example = new TestRule() { public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { wasRun = true; base.evaluate(); } ; }; } }; @Test public void nothing() { } } @Test public void ruleIsIntroducedAndEvaluated() { wasRun = false; JUnitCore.runClasses(ExampleTest.class); assertTrue(wasRun); } @SuppressWarnings("deprecation") public static class BothKindsOfRule implements TestRule, org.junit.rules.MethodRule { public int applications = 0; public Statement apply(Statement base, FrameworkMethod method, Object target) { applications++; return base; } public Statement apply(Statement base, Description description) { applications++; return base; } } public static class OneFieldTwoKindsOfRule { @Rule public BothKindsOfRule both = new BothKindsOfRule(); @Test public void onlyOnce() { assertEquals(1, both.applications); } } @Test public void onlyApplyOnceEvenIfImplementsBothInterfaces() { assertTrue(JUnitCore.runClasses(OneFieldTwoKindsOfRule.class).wasSuccessful()); } public static class SonOfExampleTest extends ExampleTest { } @Test public void ruleIsIntroducedAndEvaluatedOnSubclass() { wasRun = false; JUnitCore.runClasses(SonOfExampleTest.class); assertTrue(wasRun); } private static int runCount; public static class MultipleRuleTest { private static class Increment implements TestRule { public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { runCount++; base.evaluate(); } ; }; } } @Rule public TestRule incrementor1 = new Increment(); @Rule public TestRule incrementor2 = new Increment(); @Test public void nothing() { } } @Test public void multipleRulesAreRun() { runCount = 0; JUnitCore.runClasses(MultipleRuleTest.class); assertEquals(2, runCount); } public static class NoRulesTest { public int x; @Test public void nothing() { } } @Test public void ignoreNonRules() { Result result = JUnitCore.runClasses(NoRulesTest.class); assertEquals(0, result.getFailureCount()); } private static String log; public static class OnFailureTest { @Rule public TestRule watcher = new TestWatcher() { @Override protected void failed(Throwable e, Description description) { log += description + " " + e.getClass().getSimpleName(); } }; @Test public void nothing() { fail(); } } @Test public void onFailure() { log = ""; Result result = JUnitCore.runClasses(OnFailureTest.class); assertEquals(String.format("nothing(%s) AssertionError", OnFailureTest.class.getName()), log); assertEquals(1, result.getFailureCount()); } public static class WatchmanTest { private static String watchedLog; @Rule public TestRule watcher = new TestWatcher() { @Override protected void failed(Throwable e, Description description) { watchedLog += description + " " + e.getClass().getSimpleName() + "\n"; } @Override protected void succeeded(Description description) { watchedLog += description + " " + "success!\n"; } }; @Test public void fails() { fail(); } @Test public void succeeds() { } } @Test public void succeeded() { WatchmanTest.watchedLog = ""; JUnitCore.runClasses(WatchmanTest.class); assertThat(WatchmanTest.watchedLog, containsString(String.format("fails(%s) AssertionError", WatchmanTest.class.getName()))); assertThat(WatchmanTest.watchedLog, containsString(String.format("succeeds(%s) success!", WatchmanTest.class.getName()))); } public static class BeforesAndAfters { private static StringBuilder watchedLog = new StringBuilder(); @Before public void before() { watchedLog.append("before "); } @Rule public TestRule watcher = new LoggingTestWatcher(watchedLog); @After public void after() { watchedLog.append("after "); } @Test public void succeeds() { watchedLog.append("test "); } } @Test public void beforesAndAfters() { BeforesAndAfters.watchedLog = new StringBuilder(); JUnitCore.runClasses(BeforesAndAfters.class); assertThat(BeforesAndAfters.watchedLog.toString(), is("starting before test after succeeded finished ")); } public static class WrongTypedField { @Rule public int x = 5; @Test public void foo() { } } @Test public void validateWrongTypedField() { assertThat(testResult(WrongTypedField.class), hasSingleFailureContaining("must implement MethodRule")); } public static class SonOfWrongTypedField extends WrongTypedField { } @Test public void validateWrongTypedFieldInSuperclass() { assertThat(testResult(SonOfWrongTypedField.class), hasSingleFailureContaining("must implement MethodRule")); } public static class PrivateRule { @SuppressWarnings("unused") @Rule private TestRule rule = new TestName(); @Test public void foo() { } } @Test public void validatePrivateRule() { assertThat(testResult(PrivateRule.class), hasSingleFailureContaining("must be public")); } public static class CustomTestName implements TestRule { public String name = null; public Statement apply(final Statement base, final Description description) { return new Statement() { @Override public void evaluate() throws Throwable { name = description.getMethodName(); base.evaluate(); } }; } } public static class UsesCustomMethodRule { @Rule public CustomTestName counter = new CustomTestName(); @Test public void foo() { assertEquals("foo", counter.name); } } @Test public void useCustomMethodRule() { assertThat(testResult(UsesCustomMethodRule.class), isSuccessful()); } public static class MethodExampleTest { private TestRule example = new TestRule() { public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { wasRun = true; base.evaluate(); } ; }; } }; @Rule public TestRule getExample() { return example; } @Test public void nothing() { } } @Test public void methodRuleIsIntroducedAndEvaluated() { wasRun = false; JUnitCore.runClasses(MethodExampleTest.class); assertTrue(wasRun); } @SuppressWarnings("deprecation") public static class MethodBothKindsOfRule implements TestRule, org.junit.rules.MethodRule { public int applications = 0; public Statement apply(Statement base, FrameworkMethod method, Object target) { applications++; return base; } public Statement apply(Statement base, Description description) { applications++; return base; } } public static class MethodOneFieldTwoKindsOfRule { private MethodBothKindsOfRule both = new MethodBothKindsOfRule(); @Rule public MethodBothKindsOfRule getBoth() { return both; } @Test public void onlyOnce() { assertEquals(1, both.applications); } } @Test public void methodOnlyApplyOnceEvenIfImplementsBothInterfaces() { assertTrue(JUnitCore.runClasses(MethodOneFieldTwoKindsOfRule.class).wasSuccessful()); } public static class MethodSonOfExampleTest extends MethodExampleTest { } @Test public void methodRuleIsIntroducedAndEvaluatedOnSubclass() { wasRun = false; JUnitCore.runClasses(MethodSonOfExampleTest.class); assertTrue(wasRun); } // private static int runCount; public static class MethodMultipleRuleTest { private static class Increment implements TestRule { public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { runCount++; base.evaluate(); } ; }; } } private TestRule incrementor1 = new Increment(); @Rule public TestRule getIncrementor1() { return incrementor1; } private TestRule incrementor2 = new Increment(); @Rule public TestRule getIncrementor2() { return incrementor2; } @Test public void nothing() { } } @Test public void methodMultipleRulesAreRun() { runCount = 0; JUnitCore.runClasses(MethodMultipleRuleTest.class); assertEquals(2, runCount); } public static class MethodNoRulesTest { public int x; @Test public void nothing() { } } @Test public void methodIgnoreNonRules() { Result result = JUnitCore.runClasses(MethodNoRulesTest.class); assertEquals(0, result.getFailureCount()); } public static class MethodOnFailureTest { private TestRule watchman = new TestWatcher() { @Override protected void failed(Throwable e, Description description) { log += description + " " + e.getClass().getSimpleName(); } }; @Rule public TestRule getWatchman() { return watchman; } @Test public void nothing() { fail(); } } @Test public void methodOnFailure() { log = ""; Result result = JUnitCore.runClasses(MethodOnFailureTest.class); assertEquals(String.format("nothing(%s) AssertionError", MethodOnFailureTest.class.getName()), log); assertEquals(1, result.getFailureCount()); } public static class MethodOnSkippedTest { private TestRule watchman = new TestWatcher() { @Override protected void skipped(AssumptionViolatedException e, Description description) { log += description + " " + e.getClass().getSimpleName(); } }; @Rule public TestRule getWatchman() { return watchman; } @Test public void nothing() { Assume.assumeTrue(false); } } @Test public void methodOnSkipped() { log = ""; Result result = JUnitCore.runClasses(MethodOnSkippedTest.class); assertEquals(String.format("nothing(%s) AssumptionViolatedException", MethodOnSkippedTest.class.getName()), log); assertEquals(0, result.getFailureCount()); assertEquals(1, result.getRunCount()); } public static class MethodWatchmanTest { private static String watchedLog; private TestRule watchman = new TestWatcher() { @Override protected void failed(Throwable e, Description description) { watchedLog += description + " " + e.getClass().getSimpleName() + "\n"; } @Override protected void succeeded(Description description) { watchedLog += description + " " + "success!\n"; } }; @Rule public TestRule getWatchman() { return watchman; } @Test public void fails() { fail(); } @Test public void succeeds() { } } @Test public void methodSucceeded() { WatchmanTest.watchedLog = ""; JUnitCore.runClasses(WatchmanTest.class); assertThat(WatchmanTest.watchedLog, containsString(String.format("fails(%s) AssertionError", WatchmanTest.class.getName()))); assertThat(WatchmanTest.watchedLog, containsString(String.format("succeeds(%s) success!", WatchmanTest.class.getName()))); } public static class MethodBeforesAndAfters { private static String watchedLog; @Before public void before() { watchedLog += "before "; } private TestRule watchman = new TestWatcher() { @Override protected void starting(Description d) { watchedLog += "starting "; } @Override protected void finished(Description d) { watchedLog += "finished "; } @Override protected void succeeded(Description d) { watchedLog += "succeeded "; } }; @Rule public TestRule getWatchman() { return watchman; } @After public void after() { watchedLog += "after "; } @Test public void succeeds() { watchedLog += "test "; } } @Test public void methodBeforesAndAfters() { MethodBeforesAndAfters.watchedLog = ""; JUnitCore.runClasses(MethodBeforesAndAfters.class); assertThat(MethodBeforesAndAfters.watchedLog, is("starting before test after succeeded finished ")); } public static class MethodWrongTypedField { @Rule public int getX() { return 5; } @Test public void foo() { } } @Test public void methodValidateWrongTypedField() { assertThat(testResult(MethodWrongTypedField.class), hasSingleFailureContaining("must return an implementation of MethodRule")); } public static class MethodSonOfWrongTypedField extends MethodWrongTypedField { } @Test public void methodValidateWrongTypedFieldInSuperclass() { assertThat(testResult(MethodSonOfWrongTypedField.class), hasSingleFailureContaining("must return an implementation of MethodRule")); } public static class MethodPrivateRule { @SuppressWarnings("unused") @Rule private TestRule getRule() { return new TestName(); } @Test public void foo() { } } @Test public void methodValidatePrivateRule() { assertThat(testResult(MethodPrivateRule.class), hasSingleFailureContaining("must be public")); } public static class MethodUsesCustomMethodRule { private CustomTestName counter = new CustomTestName(); @Rule public CustomTestName getCounter() { return counter; } @Test public void foo() { assertEquals("foo", counter.name); } } @Test public void methodUseCustomMethodRule() { assertThat(testResult(MethodUsesCustomMethodRule.class), isSuccessful()); } private static final List orderList = new LinkedList(); private static class OrderTestRule implements TestRule { private String name; public OrderTestRule(String name) { this.name = name; } public Statement apply(final Statement base, final Description description) { return new Statement() { @Override public void evaluate() throws Throwable { orderList.add(name); base.evaluate(); } }; } } ; public static class UsesFieldAndMethodRule { @Rule public OrderTestRule orderMethod() { return new OrderTestRule("orderMethod"); } @Rule public OrderTestRule orderField = new OrderTestRule("orderField"); @Test public void foo() { assertEquals("orderField", orderList.get(0)); assertEquals("orderMethod", orderList.get(1)); } } @Test public void usesFieldAndMethodRule() { orderList.clear(); assertThat(testResult(UsesFieldAndMethodRule.class), isSuccessful()); } public static class MultipleCallsTest implements TestRule { public int applications = 0; public Statement apply(Statement base, Description description) { applications++; return base; } } public static class CallMethodOnlyOnceRule { int countOfMethodCalls = 0; private static class Dummy implements TestRule { public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { base.evaluate(); } ; }; } } @Rule public Dummy both() { countOfMethodCalls++; return new Dummy(); } @Test public void onlyOnce() { assertEquals(1, countOfMethodCalls); } } @Test public void testCallMethodOnlyOnceRule() { assertTrue(JUnitCore.runClasses(CallMethodOnlyOnceRule.class).wasSuccessful()); } } junit4-4.11/src/test/java/org/junit/tests/experimental/rules/NameRulesTest.java0000644000175000017500000000226012050524441027177 0ustar ebourgebourgpackage org.junit.tests.experimental.rules; import static org.junit.Assert.assertEquals; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.rules.TestName; import org.junit.runner.RunWith; @RunWith(Enclosed.class) public class NameRulesTest { public static class TestNames { @Rule public TestName name = new TestName(); @Test public void testA() { assertEquals("testA", name.getMethodName()); } @Test public void testB() { assertEquals("testB", name.getMethodName()); } } public static class BeforeAndAfterTest { @Rule public TestName name = new TestName(); private final String expectedName = "x"; @Before public void setUp() { assertEquals(expectedName, name.getMethodName()); } @Test public void x() { assertEquals(expectedName, name.getMethodName()); } @After public void tearDown() { assertEquals(expectedName, name.getMethodName()); } } } junit4-4.11/src/test/java/org/junit/tests/experimental/rules/TemporaryFolderUsageTest.java0000644000175000017500000001454212050524441031415 0ustar ebourgebourgpackage org.junit.tests.experimental.rules; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; /** * TemporaryFolderUsageTest provides tests for API usage correctness * and ensure implementation symmetry of public methods against a root folder. */ public class TemporaryFolderUsageTest { private TemporaryFolder tempFolder; @Rule public final ExpectedException thrown = ExpectedException.none(); @Before public void setUp() { tempFolder = new TemporaryFolder(); } @After public void tearDown() { tempFolder.delete(); } @Test(expected = IllegalStateException.class) public void getRootShouldThrowIllegalStateExceptionIfCreateWasNotInvoked() { new TemporaryFolder().getRoot(); } @Test(expected = IllegalStateException.class) public void newFileThrowsIllegalStateExceptionIfCreateWasNotInvoked() throws IOException { new TemporaryFolder().newFile(); } @Test(expected = IllegalStateException.class) public void newFileWithGivenNameThrowsIllegalStateExceptionIfCreateWasNotInvoked() throws IOException { new TemporaryFolder().newFile("MyFile.txt"); } @Test public void newFileWithGivenFilenameThrowsIllegalArgumentExceptionIfFileExists() throws IOException { tempFolder.create(); tempFolder.newFile("MyFile.txt"); thrown.expect(IOException.class); thrown.expectMessage("a file with the name 'MyFile.txt' already exists in the test folder"); tempFolder.newFile("MyFile.txt"); } @Test(expected = IllegalStateException.class) public void newFolderThrowsIllegalStateExceptionIfCreateWasNotInvoked() throws IOException { new TemporaryFolder().newFolder(); } @Test(expected = IllegalStateException.class) public void newFolderWithGivenPathThrowsIllegalStateExceptionIfCreateWasNotInvoked() throws IOException { new TemporaryFolder().newFolder("level1", "level2", "level3"); } @Test public void newFolderWithGivenFolderThrowsIllegalArgumentExceptionIfFolderExists() throws IOException { tempFolder.create(); tempFolder.newFolder("level1"); thrown.expect(IOException.class); thrown.expectMessage("a folder with the name 'level1' already exists"); tempFolder.newFolder("level1"); } @Test public void newFolderWithGivenPathThrowsIllegalArgumentExceptionIfPathExists() throws IOException { tempFolder.create(); tempFolder.newFolder("level1", "level2", "level3"); thrown.expect(IOException.class); thrown.expectMessage("a folder with the name 'level3' already exists"); tempFolder.newFolder("level1", "level2", "level3"); } @Test public void createInitializesRootFolder() throws IOException { tempFolder.create(); assertFileExists(tempFolder.getRoot()); } @Test public void deleteShouldDoNothingIfRootFolderWasNotInitialized() { tempFolder.delete(); } @Test public void deleteRemovesRootFolder() throws IOException { tempFolder.create(); tempFolder.delete(); assertFileDoesNotExist(tempFolder.getRoot()); } @Test public void newRandomFileIsCreatedUnderRootFolder() throws IOException { tempFolder.create(); File f = tempFolder.newFile(); assertFileExists(f); assertFileCreatedUnderRootFolder("Random file", f); } @Test public void newNamedFileIsCreatedUnderRootFolder() throws IOException { final String fileName = "SampleFile.txt"; tempFolder.create(); File f = tempFolder.newFile(fileName); assertFileExists(f); assertFileCreatedUnderRootFolder("Named file", f); assertThat("file name", f.getName(), equalTo(fileName)); } @Test public void newRandomFolderIsCreatedUnderRootFolder() throws IOException { tempFolder.create(); File f = tempFolder.newFolder(); assertFileExists(f); assertFileCreatedUnderRootFolder("Random folder", f); } @Test public void newNestedFoldersCreatedUnderRootFolder() throws IOException { tempFolder.create(); File f = tempFolder.newFolder("top", "middle", "bottom"); assertFileExists(f); assertParentFolderForFileIs(f, new File(tempFolder.getRoot(), "top/middle")); assertParentFolderForFileIs(f.getParentFile(), new File(tempFolder.getRoot(), "top")); assertFileCreatedUnderRootFolder("top", f.getParentFile() .getParentFile()); } @Test public void canSetTheBaseFileForATemporaryFolder() throws IOException { File tempDir = createTemporaryFolder(); TemporaryFolder folder = new TemporaryFolder(tempDir); folder.create(); assertThat(tempDir, is(folder.getRoot().getParentFile())); } private File createTemporaryFolder() throws IOException { File tempDir = File.createTempFile("junit", "tempFolder"); assertTrue("Unable to delete temporary file", tempDir.delete()); assertTrue("Unable to create temp directory", tempDir.mkdir()); return tempDir; } private void assertFileDoesNotExist(File file) { checkFileExists("exists", file, false); } private void checkFileExists(String msg, File file, boolean exists) { assertThat("File is null", file, is(notNullValue())); assertThat("File '" + file.getAbsolutePath() + "' " + msg, file.exists(), is(exists)); } private void assertFileExists(File file) { checkFileExists("does not exist", file, true); } private void assertFileCreatedUnderRootFolder(String msg, File f) { assertParentFolderForFileIs(f, tempFolder.getRoot()); } private void assertParentFolderForFileIs(File f, File parentFolder) { assertThat("'" + f.getAbsolutePath() + "': not under root", f.getParentFile(), is(parentFolder)); } } junit4-4.11/src/test/java/org/junit/tests/experimental/rules/RuleChainTest.java0000644000175000017500000000337512050524441027166 0ustar ebourgebourgpackage org.junit.tests.experimental.rules; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.experimental.results.PrintableResult.testResult; import static org.junit.rules.RuleChain.outerRule; import java.util.ArrayList; import java.util.List; import org.junit.Rule; import org.junit.Test; import org.junit.rules.RuleChain; import org.junit.rules.TestWatcher; import org.junit.runner.Description; public class RuleChainTest { private static final List LOG = new ArrayList(); private static class LoggingRule extends TestWatcher { private final String label; public LoggingRule(String label) { this.label = label; } @Override protected void starting(Description description) { LOG.add("starting " + label); } @Override protected void finished(Description description) { LOG.add("finished " + label); } } public static class UseRuleChain { @Rule public final RuleChain chain = outerRule(new LoggingRule("outer rule")) .around(new LoggingRule("middle rule")).around( new LoggingRule("inner rule")); @Test public void example() { assertTrue(true); } } @Test public void executeRulesInCorrectOrder() throws Exception { testResult(UseRuleChain.class); List expectedLog = asList("starting outer rule", "starting middle rule", "starting inner rule", "finished inner rule", "finished middle rule", "finished outer rule"); assertEquals(expectedLog, LOG); } }junit4-4.11/src/test/java/org/junit/tests/experimental/rules/ExternalResourceRuleTest.java0000644000175000017500000000227312050524441031432 0ustar ebourgebourgpackage org.junit.tests.experimental.rules; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.experimental.results.PrintableResult.testResult; import static org.junit.experimental.results.ResultMatchers.isSuccessful; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExternalResource; public class ExternalResourceRuleTest { private static String callSequence; public static class UsesExternalResource { @Rule public ExternalResource resource = new ExternalResource() { @Override protected void before() throws Throwable { callSequence += "before "; } ; @Override protected void after() { callSequence += "after "; } ; }; @Test public void testFoo() { callSequence += "test "; } } @Test public void externalResourceGeneratesCorrectSequence() { callSequence = ""; assertThat(testResult(UsesExternalResource.class), isSuccessful()); assertEquals("before test after ", callSequence); } } junit4-4.11/src/test/java/org/junit/tests/experimental/rules/RuleFieldValidatorTest.java0000644000175000017500000001540112050524441031026 0ustar ebourgebourgpackage org.junit.tests.experimental.rules; import static org.junit.Assert.assertEquals; import static org.junit.internal.runners.rules.RuleFieldValidator.CLASS_RULE_METHOD_VALIDATOR; import static org.junit.internal.runners.rules.RuleFieldValidator.CLASS_RULE_VALIDATOR; import static org.junit.internal.runners.rules.RuleFieldValidator.RULE_METHOD_VALIDATOR; import static org.junit.internal.runners.rules.RuleFieldValidator.RULE_VALIDATOR; import java.util.ArrayList; import java.util.List; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.MethodRule; import org.junit.rules.TemporaryFolder; import org.junit.rules.TestRule; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; import org.junit.runners.model.TestClass; @SuppressWarnings("deprecation") public class RuleFieldValidatorTest { private final List errors = new ArrayList(); @Test public void rejectProtectedClassRule() { TestClass target = new TestClass(TestWithProtectedClassRule.class); CLASS_RULE_VALIDATOR.validate(target, errors); assertOneErrorWithMessage("The @ClassRule 'temporaryFolder' must be public."); } public static class TestWithProtectedClassRule { @ClassRule protected static TestRule temporaryFolder = new TemporaryFolder(); } @Test public void rejectNonStaticClassRule() { TestClass target = new TestClass(TestWithNonStaticClassRule.class); CLASS_RULE_VALIDATOR.validate(target, errors); assertOneErrorWithMessage("The @ClassRule 'temporaryFolder' must be static."); } public static class TestWithNonStaticClassRule { @ClassRule public TestRule temporaryFolder = new TemporaryFolder(); } @Test public void acceptNonStaticTestRule() { TestClass target = new TestClass(TestWithNonStaticTestRule.class); RULE_VALIDATOR.validate(target, errors); assertNumberOfErrors(0); } public static class TestWithNonStaticTestRule { @Rule public TestRule temporaryFolder = new TemporaryFolder(); } @Test public void rejectStaticTestRule() { TestClass target = new TestClass(TestWithStaticTestRule.class); RULE_VALIDATOR.validate(target, errors); assertOneErrorWithMessage("The @Rule 'temporaryFolder' must not be static."); } public static class TestWithStaticTestRule { @Rule public static TestRule temporaryFolder = new TemporaryFolder(); } @Test public void acceptMethodRule() throws Exception { TestClass target = new TestClass(TestWithMethodRule.class); RULE_VALIDATOR.validate(target, errors); assertNumberOfErrors(0); } public static class TestWithMethodRule { @Rule public MethodRule temporaryFolder = new MethodRule() { public Statement apply(Statement base, FrameworkMethod method, Object target) { return null; } }; } @Test public void rejectArbitraryObjectWithRuleAnnotation() throws Exception { TestClass target = new TestClass(TestWithArbitraryObjectWithRuleAnnotation.class); RULE_VALIDATOR.validate(target, errors); assertOneErrorWithMessage("The @Rule 'arbitraryObject' must implement MethodRule or TestRule."); } public static class TestWithArbitraryObjectWithRuleAnnotation { @Rule public Object arbitraryObject = 1; } @Test public void methodRejectProtectedClassRule() { TestClass target = new TestClass(MethodTestWithProtectedClassRule.class); CLASS_RULE_METHOD_VALIDATOR.validate(target, errors); assertOneErrorWithMessage("The @ClassRule 'getTemporaryFolder' must be public."); } public static class MethodTestWithProtectedClassRule { @ClassRule protected static TestRule getTemporaryFolder() { return new TemporaryFolder(); } } @Test public void methodRejectNonStaticClassRule() { TestClass target = new TestClass(MethodTestWithNonStaticClassRule.class); CLASS_RULE_METHOD_VALIDATOR.validate(target, errors); assertOneErrorWithMessage("The @ClassRule 'getTemporaryFolder' must be static."); } public static class MethodTestWithNonStaticClassRule { @ClassRule public TestRule getTemporaryFolder() { return new TemporaryFolder(); } } @Test public void acceptMethodNonStaticTestRule() { TestClass target = new TestClass(TestMethodWithNonStaticTestRule.class); RULE_METHOD_VALIDATOR.validate(target, errors); assertNumberOfErrors(0); } public static class TestMethodWithNonStaticTestRule { @Rule public TestRule getTemporaryFolder() { return new TemporaryFolder(); } } @Test public void rejectMethodStaticTestRule() { TestClass target = new TestClass(TestMethodWithStaticTestRule.class); RULE_METHOD_VALIDATOR.validate(target, errors); assertOneErrorWithMessage("The @Rule 'getTemporaryFolder' must not be static."); } public static class TestMethodWithStaticTestRule { @Rule public static TestRule getTemporaryFolder() { return new TemporaryFolder(); } } @Test public void methodAcceptMethodRuleMethod() throws Exception { TestClass target = new TestClass(MethodTestWithMethodRule.class); RULE_METHOD_VALIDATOR.validate(target, errors); assertNumberOfErrors(0); } public static class MethodTestWithMethodRule { @Rule public MethodRule getTemporaryFolder() { return new MethodRule() { public Statement apply(Statement base, FrameworkMethod method, Object target) { return null; } }; } } @Test public void methodRejectArbitraryObjectWithRuleAnnotation() throws Exception { TestClass target = new TestClass(MethodTestWithArbitraryObjectWithRuleAnnotation.class); RULE_METHOD_VALIDATOR.validate(target, errors); assertOneErrorWithMessage("The @Rule 'getArbitraryObject' must return an implementation of MethodRule or TestRule."); } public static class MethodTestWithArbitraryObjectWithRuleAnnotation { @Rule public Object getArbitraryObject() { return 1; } } private void assertOneErrorWithMessage(String message) { assertNumberOfErrors(1); assertEquals("Wrong error message:", message, errors.get(0).getMessage()); } private void assertNumberOfErrors(int numberOfErrors) { assertEquals("Wrong number of errors:", numberOfErrors, errors.size()); } } junit4-4.11/src/test/java/org/junit/tests/experimental/rules/EventCollector.java0000644000175000017500000001343312050524441027400 0ustar ebourgebourgpackage org.junit.tests.experimental.rules; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.core.IsEqual.equalTo; import java.util.ArrayList; import java.util.List; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.junit.runner.Description; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; class EventCollector extends RunListener { static Matcher everyTestRunSuccessful() { return allOf(hasNoFailure(), hasNoAssumptionFailure()); } private static Matcher hasNumberOfFailures( final int numberOfFailures) { return new TypeSafeMatcher() { @Override public boolean matchesSafely(EventCollector item) { return item.fFailures.size() == numberOfFailures; } public void describeTo(org.hamcrest.Description description) { description.appendText("has "); description.appendValue(numberOfFailures); description.appendText(" failures"); } }; } static Matcher hasSingleFailure() { return hasNumberOfFailures(1); } static Matcher hasNoFailure() { return hasNumberOfFailures(0); } private static Matcher hasNumberOfAssumptionFailures( final int numberOfFailures) { return new TypeSafeMatcher() { @Override public boolean matchesSafely(EventCollector item) { return item.fAssumptionFailures.size() == numberOfFailures; } public void describeTo(org.hamcrest.Description description) { description.appendText("has "); description.appendValue(numberOfFailures); description.appendText(" assumption failures"); } }; } static Matcher hasSingleAssumptionFailure() { return hasNumberOfAssumptionFailures(1); } static Matcher hasNoAssumptionFailure() { return hasNumberOfAssumptionFailures(0); } static Matcher hasSingleFailureWithMessage(String message) { return hasSingleFailureWithMessage(equalTo(message)); } static Matcher hasSingleFailureWithMessage( final Matcher messageMatcher) { return new TypeSafeMatcher() { @Override public boolean matchesSafely(EventCollector item) { return hasSingleFailure().matches(item) && messageMatcher.matches(item.fFailures.get(0) .getMessage()); } public void describeTo(org.hamcrest.Description description) { description.appendText("has single failure with message "); messageMatcher.describeTo(description); } }; } static Matcher failureIs(final Matcher exceptionMatcher) { return new TypeSafeMatcher() { @Override public boolean matchesSafely(EventCollector item) { for (Failure f : item.fFailures) { return exceptionMatcher.matches(f.getException()); } return false; } public void describeTo(org.hamcrest.Description description) { description.appendText("failure is "); exceptionMatcher.describeTo(description); } }; } private final List fTestRunsStarted = new ArrayList(); private final List fTestRunsFinished = new ArrayList(); private final List fTestsStarted = new ArrayList(); private final List fTestsFinished = new ArrayList(); private final List fFailures = new ArrayList(); private final List fAssumptionFailures = new ArrayList(); private final List fTestsIgnored = new ArrayList(); @Override public void testRunStarted(Description description) throws Exception { fTestRunsStarted.add(description); } @Override public void testRunFinished(Result result) throws Exception { fTestRunsFinished.add(result); } @Override public void testStarted(Description description) throws Exception { fTestsStarted.add(description); } @Override public void testFinished(Description description) throws Exception { fTestsFinished.add(description); } @Override public void testFailure(Failure failure) throws Exception { fFailures.add(failure); } @Override public void testAssumptionFailure(Failure failure) { fAssumptionFailures.add(failure); } @Override public void testIgnored(Description description) throws Exception { fTestsIgnored.add(description); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(fTestRunsStarted.size()); sb.append(" test runs started, "); sb.append(fTestRunsFinished.size()); sb.append(" test runs finished, "); sb.append(fTestsStarted.size()); sb.append(" tests started, "); sb.append(fTestsFinished.size()); sb.append(" tests finished, "); sb.append(fFailures.size()); sb.append(" failures, "); sb.append(fAssumptionFailures.size()); sb.append(" assumption failures, "); sb.append(fTestsIgnored.size()); sb.append(" tests ignored"); return sb.toString(); } } junit4-4.11/src/test/java/org/junit/tests/experimental/rules/LoggingTestWatcher.java0000644000175000017500000000132612050524441030212 0ustar ebourgebourgpackage org.junit.tests.experimental.rules; import org.junit.rules.TestWatcher; import org.junit.runner.Description; class LoggingTestWatcher extends TestWatcher { private final StringBuilder log; LoggingTestWatcher(StringBuilder log) { this.log = log; } @Override protected void succeeded(Description description) { log.append("succeeded "); } @Override protected void failed(Throwable e, Description description) { log.append("failed "); } @Override protected void starting(Description description) { log.append("starting "); } @Override protected void finished(Description description) { log.append("finished "); } }junit4-4.11/src/test/java/org/junit/tests/experimental/rules/ExpectedExceptionTest.java0000644000175000017500000003215012050524441030725 0ustar ebourgebourgpackage org.junit.tests.experimental.rules; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.any; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.CoreMatchers.startsWith; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.junit.Assume.assumeTrue; import static org.junit.rules.ExpectedException.none; import static org.junit.tests.experimental.rules.EventCollector.everyTestRunSuccessful; import static org.junit.tests.experimental.rules.EventCollector.hasSingleAssumptionFailure; import static org.junit.tests.experimental.rules.EventCollector.hasSingleFailure; import static org.junit.tests.experimental.rules.EventCollector.hasSingleFailureWithMessage; import java.util.Collection; import org.hamcrest.CoreMatchers; import org.hamcrest.Matcher; import org.junit.Rule; import org.junit.Test; import org.junit.internal.AssumptionViolatedException; import org.junit.rules.ExpectedException; import org.junit.runner.JUnitCore; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class ExpectedExceptionTest { private static final String ARBITRARY_MESSAGE = "arbitrary message"; @Parameters public static Collection testsWithEventMatcher() { return asList(new Object[][]{ {EmptyTestExpectingNoException.class, everyTestRunSuccessful()}, {ThrowExceptionWithExpectedType.class, everyTestRunSuccessful()}, {ThrowExceptionWithExpectedPartOfMessage.class, everyTestRunSuccessful()}, { ThrowExceptionWithWrongType.class, hasSingleFailureWithMessage(startsWith("\nExpected: an instance of java.lang.NullPointerException"))}, { HasWrongMessage.class, hasSingleFailureWithMessage(startsWith("\nExpected: exception with message a string containing \"expectedMessage\"\n" + " but: message was \"actualMessage\""))}, { ThrowNoExceptionButExpectExceptionWithType.class, hasSingleFailureWithMessage("Expected test to throw an instance of java.lang.NullPointerException")}, {WronglyExpectsExceptionMessage.class, hasSingleFailure()}, {ExpectsSubstring.class, everyTestRunSuccessful()}, { ExpectsSubstringNullMessage.class, hasSingleFailureWithMessage(startsWith("\nExpected: exception with message a string containing \"anything!\""))}, {ExpectsMessageMatcher.class, everyTestRunSuccessful()}, { ExpectedMessageMatcherFails.class, hasSingleFailureWithMessage(startsWith("\nExpected: exception with message \"Wrong start\""))}, {ExpectsMatcher.class, everyTestRunSuccessful()}, {ThrowExpectedAssumptionViolatedException.class, everyTestRunSuccessful()}, {ThrowAssumptionViolatedExceptionButExpectOtherType.class, hasSingleFailure()}, { ThrowAssumptionViolatedExceptionButExpectOtherType.class, hasSingleFailureWithMessage(containsString("Stacktrace was: org.junit.internal.AssumptionViolatedException"))}, {ViolateAssumptionAndExpectException.class, hasSingleAssumptionFailure()}, {ThrowExpectedAssertionError.class, everyTestRunSuccessful()}, { ThrowUnexpectedAssertionError.class, hasSingleFailureWithMessage(startsWith("\nExpected: an instance of java.lang.NullPointerException"))}, {FailAndDontHandleAssertinErrors.class, hasSingleFailureWithMessage(ARBITRARY_MESSAGE)}, { ExpectsMultipleMatchers.class, hasSingleFailureWithMessage(startsWith("\nExpected: (an instance of java.lang.IllegalArgumentException and exception with message a string containing \"Ack!\")"))}, {ThrowExceptionWithMatchingCause.class, everyTestRunSuccessful()}, {ThrowExpectedNullCause.class, everyTestRunSuccessful()}, { ThrowUnexpectedCause.class, hasSingleFailureWithMessage(CoreMatchers.allOf( startsWith("\nExpected: ("), containsString("exception with cause is "), containsString("cause was "), containsString("Stacktrace was: java.lang.IllegalArgumentException: Ack!"), containsString("Caused by: java.lang.NullPointerException: an unexpected cause")))} }); } private final Class classUnderTest; private final Matcher matcher; public ExpectedExceptionTest(Class classUnderTest, Matcher matcher) { this.classUnderTest = classUnderTest; this.matcher = matcher; } @Test public void runTestAndVerifyResult() { EventCollector collector = new EventCollector(); JUnitCore core = new JUnitCore(); core.addListener(collector); core.run(classUnderTest); assertThat(collector, matcher); } public static class EmptyTestExpectingNoException { @Rule public ExpectedException thrown = none(); @Test public void throwsNothing() { } } public static class ThrowExceptionWithExpectedType { @Rule public ExpectedException thrown = none(); @Test public void throwsNullPointerException() { thrown.expect(NullPointerException.class); throw new NullPointerException(); } } public static class ThrowExceptionWithExpectedPartOfMessage { @Rule public ExpectedException thrown = none(); @Test public void throwsNullPointerExceptionWithMessage() { thrown.expect(NullPointerException.class); thrown.expectMessage(ARBITRARY_MESSAGE); throw new NullPointerException(ARBITRARY_MESSAGE + "something else"); } } public static class ThrowExceptionWithWrongType { @Rule public ExpectedException thrown = none(); @Test public void throwsNullPointerException() { thrown.expect(NullPointerException.class); throw new IllegalArgumentException(); } } public static class HasWrongMessage { @Rule public ExpectedException thrown = none(); @Test public void throwsNullPointerException() { thrown.expectMessage("expectedMessage"); throw new IllegalArgumentException("actualMessage"); } } public static class ThrowNoExceptionButExpectExceptionWithType { @Rule public ExpectedException thrown = none(); @Test public void doesntThrowNullPointerException() { thrown.expect(NullPointerException.class); } } public static class WronglyExpectsExceptionMessage { @Rule public ExpectedException thrown = none(); @Test public void doesntThrowAnything() { thrown.expectMessage("anything!"); } } public static class ExpectsSubstring { @Rule public ExpectedException thrown = none(); @Test public void throwsMore() { thrown.expectMessage("anything!"); throw new NullPointerException( "This could throw anything! (as long as it has the right substring)"); } } public static class ExpectsSubstringNullMessage { @Rule public ExpectedException thrown = none(); @Test public void throwsMore() { thrown.expectMessage("anything!"); throw new NullPointerException(); } } public static class ExpectsMessageMatcher { @Rule public ExpectedException thrown = none(); @Test public void throwsMore() { thrown.expectMessage(startsWith(ARBITRARY_MESSAGE)); throw new NullPointerException(ARBITRARY_MESSAGE + "!"); } } public static class ExpectedMessageMatcherFails { @Rule public ExpectedException thrown = none(); @Test public void throwsMore() { thrown.expectMessage(equalTo("Wrong start")); throw new NullPointerException("Back!"); } } public static class ExpectsMatcher { @Rule public ExpectedException thrown = none(); @Test public void throwsMore() { thrown.expect(any(Exception.class)); throw new NullPointerException("Ack!"); } } public static class ExpectsMultipleMatchers { @Rule public ExpectedException thrown = none(); @Test public void throwsMore() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Ack!"); throw new NullPointerException("Ack!"); } } public static class FailAndDontHandleAssertinErrors { @Rule public ExpectedException thrown = none(); @Test public void violatedAssumption() { thrown.expect(IllegalArgumentException.class); fail(ARBITRARY_MESSAGE); } } public static class ThrowUnexpectedAssertionError { @Rule public ExpectedException thrown = none(); @Test public void wrongException() { thrown.handleAssertionErrors(); thrown.expect(NullPointerException.class); throw new AssertionError("the unexpected assertion error"); } } public static class ThrowExpectedAssertionError { @Rule public ExpectedException thrown = none(); @Test public void wrongException() { thrown.handleAssertionErrors(); thrown.expect(AssertionError.class); throw new AssertionError("the expected assertion error"); } } public static class ViolateAssumptionAndExpectException { @Rule public ExpectedException thrown = none(); @Test public void violatedAssumption() { // expect an exception, which is not an AssumptionViolatedException thrown.expect(NullPointerException.class); assumeTrue(false); } } public static class ThrowAssumptionViolatedExceptionButExpectOtherType { @Rule public ExpectedException thrown = none(); @Test public void wrongException() { thrown.handleAssumptionViolatedExceptions(); thrown.expect(NullPointerException.class); throw new AssumptionViolatedException(""); } } public static class ThrowExpectedAssumptionViolatedException { @Rule public ExpectedException thrown = none(); @Test public void throwExpectAssumptionViolatedException() { thrown.handleAssumptionViolatedExceptions(); thrown.expect(AssumptionViolatedException.class); throw new AssumptionViolatedException(""); } } public static class ThrowExceptionWithMatchingCause { @Rule public ExpectedException thrown = none(); @Test public void throwExceptionWithMatchingCause() { NullPointerException expectedCause = new NullPointerException("expected cause"); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Ack!"); thrown.expectCause(is(expectedCause)); throw new IllegalArgumentException("Ack!", expectedCause); } } public static class ThrowExpectedNullCause { @Rule public ExpectedException thrown = none(); @Test public void throwExpectedNullCause() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Ack!"); thrown.expectCause(nullValue(Throwable.class)); throw new IllegalArgumentException("Ack!"); } } public static class ThrowUnexpectedCause { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void throwWithCause() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Ack!"); thrown.expectCause(is(new NullPointerException("expected cause"))); throw new IllegalArgumentException("Ack!", new NullPointerException("an unexpected cause")); } } }junit4-4.11/src/test/java/org/junit/tests/experimental/rules/TempFolderRuleTest.java0000644000175000017500000001755412050524441030211 0ustar ebourgebourgpackage org.junit.tests.experimental.rules; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.core.IsNot.not; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.experimental.results.PrintableResult.testResult; import static org.junit.experimental.results.ResultMatchers.failureCountIs; import static org.junit.experimental.results.ResultMatchers.isSuccessful; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public class TempFolderRuleTest { private static File[] createdFiles = new File[20]; public static class HasTempFolder { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void testUsingTempFolder() throws IOException { createdFiles[0] = folder.newFile("myfile.txt"); assertTrue(createdFiles[0].exists()); } } @Test public void tempFolderIsDeleted() { assertThat(testResult(HasTempFolder.class), isSuccessful()); assertFalse(createdFiles[0].exists()); } public static class CreatesSubFolder { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void testUsingTempFolderStringReflection() throws Exception { String subfolder = "subfolder"; String filename = "a.txt"; // force usage of folder.newFolder(String), // check is available and works, to avoid a potential NoSuchMethodError with non-recompiled code. Method method = folder.getClass().getMethod("newFolder", new Class[]{String.class}); createdFiles[0] = (File) method.invoke(folder, subfolder); new File(createdFiles[0], filename).createNewFile(); File expectedFile = new File(folder.getRoot(), join(subfolder, filename)); assertTrue(expectedFile.exists()); } @Test public void testUsingTempFolderString() throws IOException { String subfolder = "subfolder"; String filename = "a.txt"; // this uses newFolder(String), ensure that a single String works createdFiles[0] = folder.newFolder(subfolder); new File(createdFiles[0], filename).createNewFile(); File expectedFile = new File(folder.getRoot(), join(subfolder, filename)); assertTrue(expectedFile.exists()); } @Test public void testUsingTempTreeFolders() throws IOException { String subfolder = "subfolder"; String anotherfolder = "anotherfolder"; String filename = "a.txt"; createdFiles[0] = folder.newFolder(subfolder, anotherfolder); new File(createdFiles[0], filename).createNewFile(); File expectedFile = new File(folder.getRoot(), join(subfolder, anotherfolder, filename)); assertTrue(expectedFile.exists()); } private String join(String... folderNames) { StringBuilder path = new StringBuilder(); for (String folderName : folderNames) { path.append(File.separator).append(folderName); } return path.toString(); } } @Test public void subFolderIsDeleted() { assertThat(testResult(CreatesSubFolder.class), isSuccessful()); assertFalse(createdFiles[0].exists()); } public static class CreatesRandomSubFolders { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void testUsingRandomTempFolders() throws IOException { for (int i = 0; i < 20; i++) { File newFolder = folder.newFolder(); assertThat(Arrays.asList(createdFiles), not(hasItem(newFolder))); createdFiles[i] = newFolder; new File(newFolder, "a.txt").createNewFile(); assertTrue(newFolder.exists()); } } } @Test public void randomSubFoldersAreDeleted() { assertThat(testResult(CreatesRandomSubFolders.class), isSuccessful()); for (File f : createdFiles) { assertFalse(f.exists()); } } public static class CreatesRandomFiles { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void testUsingRandomTempFiles() throws IOException { for (int i = 0; i < 20; i++) { File newFile = folder.newFile(); assertThat(Arrays.asList(createdFiles), not(hasItem(newFile))); createdFiles[i] = newFile; assertTrue(newFile.exists()); } } } @Test public void randomFilesAreDeleted() { assertThat(testResult(CreatesRandomFiles.class), isSuccessful()); for (File f : createdFiles) { assertFalse(f.exists()); } } @Test public void recursiveDeleteFolderWithOneElement() throws IOException { TemporaryFolder folder = new TemporaryFolder(); folder.create(); File file = folder.newFile("a"); folder.delete(); assertFalse(file.exists()); assertFalse(folder.getRoot().exists()); } @Test public void recursiveDeleteFolderWithOneRandomElement() throws IOException { TemporaryFolder folder = new TemporaryFolder(); folder.create(); File file = folder.newFile(); folder.delete(); assertFalse(file.exists()); assertFalse(folder.getRoot().exists()); } @Test public void recursiveDeleteFolderWithZeroElements() throws IOException { TemporaryFolder folder = new TemporaryFolder(); folder.create(); folder.delete(); assertFalse(folder.getRoot().exists()); } public static class NameClashes { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void fileWithFileClash() throws IOException { folder.newFile("something.txt"); folder.newFile("something.txt"); } @Test public void fileWithFolderTest() throws IOException { folder.newFolder("dummy"); folder.newFile("dummy"); } } @Test public void nameClashesResultInTestFailures() { assertThat(testResult(NameClashes.class), failureCountIs(2)); } private static final String GET_ROOT_DUMMY = "dummy-getRoot"; private static final String NEW_FILE_DUMMY = "dummy-newFile"; private static final String NEW_FOLDER_DUMMY = "dummy-newFolder"; public static class IncorrectUsage { public TemporaryFolder folder = new TemporaryFolder(); @Test public void testGetRoot() throws IOException { new File(folder.getRoot(), GET_ROOT_DUMMY).createNewFile(); } @Test public void testNewFile() throws IOException { folder.newFile(NEW_FILE_DUMMY); } @Test public void testNewFolder() throws IOException { folder.newFolder(NEW_FOLDER_DUMMY); } } @Test public void incorrectUsageWithoutApplyingTheRuleShouldNotPolluteTheCurrentWorkingDirectory() { assertThat(testResult(IncorrectUsage.class), failureCountIs(3)); assertFalse("getRoot should have failed early", new File(GET_ROOT_DUMMY).exists()); assertFalse("newFile should have failed early", new File(NEW_FILE_DUMMY).exists()); assertFalse("newFolder should have failed early", new File(NEW_FOLDER_DUMMY).exists()); } @After public void cleanCurrentWorkingDirectory() { new File(GET_ROOT_DUMMY).delete(); new File(NEW_FILE_DUMMY).delete(); new File(NEW_FOLDER_DUMMY).delete(); } } junit4-4.11/src/test/java/org/junit/tests/experimental/rules/TestWatchmanTest.java0000644000175000017500000000372012050524441027710 0ustar ebourgebourgpackage org.junit.tests.experimental.rules; import static junit.framework.Assert.fail; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assume.assumeTrue; import static org.junit.runner.JUnitCore.runClasses; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestWatchman; import org.junit.runners.model.FrameworkMethod; @SuppressWarnings("deprecation") public class TestWatchmanTest { public static class ViolatedAssumptionTest { @Rule public static LoggingTestWatchman watchman = new LoggingTestWatchman(); @Test public void succeeds() { assumeTrue(false); } } @Test public void neitherLogSuccessNorFailedForViolatedAssumption() { runClasses(ViolatedAssumptionTest.class); assertThat(ViolatedAssumptionTest.watchman.log.toString(), is("starting finished ")); } public static class FailingTest { @Rule public static LoggingTestWatchman watchman = new LoggingTestWatchman(); @Test public void succeeds() { fail(); } } @Test public void logFailingTest() { runClasses(FailingTest.class); assertThat(FailingTest.watchman.log.toString(), is("starting failed finished ")); } private static class LoggingTestWatchman extends TestWatchman { private final StringBuilder log = new StringBuilder(); @Override public void succeeded(FrameworkMethod method) { log.append("succeeded "); } @Override public void failed(Throwable e, FrameworkMethod method) { log.append("failed "); } @Override public void starting(FrameworkMethod method) { log.append("starting "); } @Override public void finished(FrameworkMethod method) { log.append("finished "); } } }junit4-4.11/src/test/java/org/junit/tests/experimental/rules/TestWatcherTest.java0000644000175000017500000001240312050524441027541 0ustar ebourgebourgpackage org.junit.tests.experimental.rules; import static junit.framework.Assert.fail; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assume.assumeTrue; import static org.junit.experimental.results.PrintableResult.testResult; import static org.junit.experimental.results.ResultMatchers.failureCountIs; import static org.junit.experimental.results.ResultMatchers.hasFailureContaining; import static org.junit.runner.JUnitCore.runClasses; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.results.PrintableResult; import org.junit.internal.AssumptionViolatedException; import org.junit.rules.TestRule; import org.junit.rules.TestWatcher; import org.junit.runner.Description; public class TestWatcherTest { public static class ViolatedAssumptionTest { private static StringBuilder watchedLog = new StringBuilder(); @Rule public TestRule watcher = new LoggingTestWatcher(watchedLog); @Test public void succeeds() { assumeTrue(false); } } @Test public void neitherLogSuccessNorFailedForViolatedAssumption() { ViolatedAssumptionTest.watchedLog = new StringBuilder(); runClasses(ViolatedAssumptionTest.class); assertThat(ViolatedAssumptionTest.watchedLog.toString(), is("starting finished ")); } public static class TestWatcherSkippedThrowsExceptionTest { @Rule public TestRule watcher = new TestWatcher() { @Override protected void skipped(AssumptionViolatedException e, Description description) { throw new RuntimeException("watcher failure"); } }; @Test public void fails() { throw new AssumptionViolatedException("test failure"); } } @Test public void testWatcherSkippedThrowsException() { PrintableResult result = testResult(TestWatcherSkippedThrowsExceptionTest.class); assertThat(result, failureCountIs(2)); assertThat(result, hasFailureContaining("test failure")); assertThat(result, hasFailureContaining("watcher failure")); } public static class FailingTest { private static StringBuilder watchedLog = new StringBuilder(); @Rule public TestRule watcher = new LoggingTestWatcher(watchedLog); @Test public void succeeds() { fail(); } } @Test public void logFailingTest() { FailingTest.watchedLog = new StringBuilder(); runClasses(FailingTest.class); assertThat(FailingTest.watchedLog.toString(), is("starting failed finished ")); } public static class TestWatcherFailedThrowsExceptionTest { @Rule public TestRule watcher = new TestWatcher() { @Override protected void failed(Throwable e, Description description) { throw new RuntimeException("watcher failure"); } }; @Test public void fails() { throw new IllegalArgumentException("test failure"); } } @Test public void testWatcherFailedThrowsException() { PrintableResult result = testResult(TestWatcherFailedThrowsExceptionTest.class); assertThat(result, failureCountIs(2)); assertThat(result, hasFailureContaining("test failure")); assertThat(result, hasFailureContaining("watcher failure")); } public static class TestWatcherStartingThrowsExceptionTest { @Rule public TestRule watcher = new TestWatcher() { @Override protected void starting(Description description) { throw new RuntimeException("watcher failure"); } }; @Test public void fails() { throw new IllegalArgumentException("test failure"); } } @Test public void testWatcherStartingThrowsException() { PrintableResult result = testResult(TestWatcherStartingThrowsExceptionTest.class); assertThat(result, failureCountIs(2)); assertThat(result, hasFailureContaining("test failure")); assertThat(result, hasFailureContaining("watcher failure")); } public static class TestWatcherFailedAndFinishedThrowsExceptionTest { @Rule public TestRule watcher = new TestWatcher() { @Override protected void failed(Throwable t, Description description) { throw new RuntimeException("watcher failed failure"); } @Override protected void finished(Description description) { throw new RuntimeException("watcher finished failure"); } }; @Test public void fails() { throw new IllegalArgumentException("test failure"); } } @Test public void testWatcherFailedAndFinishedThrowsException() { PrintableResult result = testResult(TestWatcherFailedAndFinishedThrowsExceptionTest.class); assertThat(result, failureCountIs(3)); assertThat(result, hasFailureContaining("test failure")); assertThat(result, hasFailureContaining("watcher failed failure")); assertThat(result, hasFailureContaining("watcher finished failure")); } }junit4-4.11/src/test/java/org/junit/tests/experimental/rules/TimeoutRuleTest.java0000644000175000017500000000234512050524441027566 0ustar ebourgebourgpackage org.junit.tests.experimental.rules; import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; import org.junit.rules.Timeout; import org.junit.runner.JUnitCore; import org.junit.runner.Result; public class TimeoutRuleTest { public static class HasGlobalTimeout { public static String log; @Rule public TestRule globalTimeout = new Timeout(20); @Test public void testInfiniteLoop1() { log += "ran1"; for (; ; ) { } } @Test public void testInfiniteLoop2() { log += "ran2"; for (; ; ) { } } } @Ignore("For gump, for now") @Test(timeout = 100) public void globalTimeoutAvoidsInfiniteLoop() { HasGlobalTimeout.log = ""; Result result = JUnitCore.runClasses(HasGlobalTimeout.class); assertEquals(2, result.getFailureCount()); assertThat(HasGlobalTimeout.log, containsString("ran1")); assertThat(HasGlobalTimeout.log, containsString("ran2")); } } junit4-4.11/src/test/java/org/junit/tests/experimental/rules/MethodRulesTest.java0000644000175000017500000001732312050524441027545 0ustar ebourgebourgpackage org.junit.tests.experimental.rules; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.experimental.results.PrintableResult.testResult; import static org.junit.experimental.results.ResultMatchers.hasSingleFailureContaining; import static org.junit.experimental.results.ResultMatchers.isSuccessful; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.MethodRule; import org.junit.rules.TestName; import org.junit.rules.TestRule; import org.junit.rules.TestWatchman; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; @SuppressWarnings("deprecation") public class MethodRulesTest { private static boolean wasRun; public static class ExampleTest { @Rule public MethodRule example = new MethodRule() { public Statement apply(final Statement base, FrameworkMethod method, Object target) { return new Statement() { @Override public void evaluate() throws Throwable { wasRun = true; base.evaluate(); } ; }; } }; @Test public void nothing() { } } @Test public void ruleIsIntroducedAndEvaluated() { wasRun = false; JUnitCore.runClasses(ExampleTest.class); assertTrue(wasRun); } public static class SonOfExampleTest extends ExampleTest { } @Test public void ruleIsIntroducedAndEvaluatedOnSubclass() { wasRun = false; JUnitCore.runClasses(SonOfExampleTest.class); assertTrue(wasRun); } private static int runCount; public static class MultipleRuleTest { private static class Increment implements MethodRule { public Statement apply(final Statement base, FrameworkMethod method, Object target) { return new Statement() { @Override public void evaluate() throws Throwable { runCount++; base.evaluate(); } ; }; } } @Rule public MethodRule incrementor1 = new Increment(); @Rule public MethodRule incrementor2 = new Increment(); @Test public void nothing() { } } @Test public void multipleRulesAreRun() { runCount = 0; JUnitCore.runClasses(MultipleRuleTest.class); assertEquals(2, runCount); } public static class NoRulesTest { public int x; @Test public void nothing() { } } @Test public void ignoreNonRules() { Result result = JUnitCore.runClasses(NoRulesTest.class); assertEquals(0, result.getFailureCount()); } private static String log; public static class OnFailureTest { @Rule public MethodRule watchman = new TestWatchman() { @Override public void failed(Throwable e, FrameworkMethod method) { log += method.getName() + " " + e.getClass().getSimpleName(); } }; @Test public void nothing() { fail(); } } @Test public void onFailure() { log = ""; Result result = JUnitCore.runClasses(OnFailureTest.class); assertEquals("nothing AssertionError", log); assertEquals(1, result.getFailureCount()); } public static class WatchmanTest { private static String watchedLog; @Rule public MethodRule watchman = new TestWatchman() { @Override public void failed(Throwable e, FrameworkMethod method) { watchedLog += method.getName() + " " + e.getClass().getSimpleName() + "\n"; } @Override public void succeeded(FrameworkMethod method) { watchedLog += method.getName() + " " + "success!\n"; } }; @Test public void fails() { fail(); } @Test public void succeeds() { } } @Test public void succeeded() { WatchmanTest.watchedLog = ""; JUnitCore.runClasses(WatchmanTest.class); assertThat(WatchmanTest.watchedLog, containsString("fails AssertionError")); assertThat(WatchmanTest.watchedLog, containsString("succeeds success!")); } public static class BeforesAndAfters { private static String watchedLog; @Before public void before() { watchedLog += "before "; } @Rule public MethodRule watchman = new TestWatchman() { @Override public void starting(FrameworkMethod method) { watchedLog += "starting "; } @Override public void finished(FrameworkMethod method) { watchedLog += "finished "; } @Override public void succeeded(FrameworkMethod method) { watchedLog += "succeeded "; } }; @After public void after() { watchedLog += "after "; } @Test public void succeeds() { watchedLog += "test "; } } @Test public void beforesAndAfters() { BeforesAndAfters.watchedLog = ""; JUnitCore.runClasses(BeforesAndAfters.class); assertThat(BeforesAndAfters.watchedLog, is("starting before test after succeeded finished ")); } public static class WrongTypedField { @Rule public int x = 5; @Test public void foo() { } } @Test public void validateWrongTypedField() { assertThat(testResult(WrongTypedField.class), hasSingleFailureContaining("must implement MethodRule")); } public static class SonOfWrongTypedField extends WrongTypedField { } @Test public void validateWrongTypedFieldInSuperclass() { assertThat(testResult(SonOfWrongTypedField.class), hasSingleFailureContaining("must implement MethodRule")); } public static class PrivateRule { @SuppressWarnings("unused") @Rule private TestRule rule = new TestName(); @Test public void foo() { } } @Test public void validatePrivateRule() { assertThat(testResult(PrivateRule.class), hasSingleFailureContaining("must be public")); } public static class CustomTestName implements TestRule { public String name = null; public Statement apply(final Statement base, final Description description) { return new Statement() { @Override public void evaluate() throws Throwable { name = description.getMethodName(); base.evaluate(); } }; } } public static class UsesCustomMethodRule { @Rule public CustomTestName counter = new CustomTestName(); @Test public void foo() { assertEquals("foo", counter.name); } } @Test public void useCustomMethodRule() { assertThat(testResult(UsesCustomMethodRule.class), isSuccessful()); } } junit4-4.11/src/test/java/org/junit/tests/experimental/ExperimentalTests.java0000644000175000017500000000266012050524441026776 0ustar ebourgebourgpackage org.junit.tests.experimental; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import org.junit.tests.experimental.results.PrintableResultTest; import org.junit.tests.experimental.results.ResultMatchersTest; import org.junit.tests.experimental.theories.ParameterSignatureTest; import org.junit.tests.experimental.theories.ParameterizedAssertionErrorTest; import org.junit.tests.experimental.theories.extendingwithstubs.StubbedTheoriesTest; import org.junit.tests.experimental.theories.runner.SuccessfulWithDataPointFields; import org.junit.tests.experimental.theories.runner.UnsuccessfulWithDataPointFields; import org.junit.tests.experimental.theories.runner.WhenNoParametersMatch; import org.junit.tests.experimental.theories.runner.WithDataPointMethod; import org.junit.tests.experimental.theories.runner.WithExtendedParameterSources; import org.junit.tests.experimental.theories.runner.WithOnlyTestAnnotations; @RunWith(Suite.class) @SuiteClasses({ParameterizedAssertionErrorTest.class, UnsuccessfulWithDataPointFields.class, SuccessfulWithDataPointFields.class, PrintableResultTest.class, ResultMatchersTest.class, WithDataPointMethod.class, ParameterSignatureTest.class, WhenNoParametersMatch.class, WithExtendedParameterSources.class, StubbedTheoriesTest.class, WithOnlyTestAnnotations.class}) public class ExperimentalTests { } junit4-4.11/src/test/java/org/junit/tests/experimental/theories/0000755000175000017500000000000012050524441024271 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/experimental/theories/AllMembersSupplierTest.java0000644000175000017500000000220512050524441031542 0ustar ebourgebourgpackage org.junit.tests.experimental.theories; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.List; import org.junit.Test; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.ParameterSignature; import org.junit.experimental.theories.PotentialAssignment; import org.junit.experimental.theories.internal.AllMembersSupplier; import org.junit.runners.model.TestClass; public class AllMembersSupplierTest { public static class HasDataPoints { @DataPoints public static Object[] objects = {1, 2}; public HasDataPoints(Object obj) { } } @Test public void dataPointsAnnotationMeansTreatAsArrayOnly() throws SecurityException, NoSuchMethodException { List valueSources = new AllMembersSupplier( new TestClass(HasDataPoints.class)) .getValueSources(ParameterSignature.signatures( HasDataPoints.class.getConstructor(Object.class)) .get(0)); assertThat(valueSources.size(), is(2)); } } junit4-4.11/src/test/java/org/junit/tests/experimental/theories/TestedOnSupplierTest.java0000644000175000017500000000206412050524441031247 0ustar ebourgebourgpackage org.junit.tests.experimental.theories; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.lang.reflect.Method; import java.util.List; import org.junit.Test; import org.junit.experimental.theories.ParameterSignature; import org.junit.experimental.theories.PotentialAssignment; import org.junit.experimental.theories.suppliers.TestedOn; import org.junit.experimental.theories.suppliers.TestedOnSupplier; public class TestedOnSupplierTest { public void foo(@TestedOn(ints = {1}) int x) { } @Test public void descriptionStatesParameterName() throws Exception { TestedOnSupplier supplier = new TestedOnSupplier(); List assignments = supplier.getValueSources(signatureOfFoo()); assertThat(assignments.get(0).getDescription(), is("ints")); } private ParameterSignature signatureOfFoo() throws NoSuchMethodException { Method method = getClass().getMethod("foo", int.class); return ParameterSignature.signatures(method).get(0); } } junit4-4.11/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/0000755000175000017500000000000012050524441030233 5ustar ebourgebourg././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootjunit4-4.11/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StringableObject.javajunit4-4.11/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StringableObject.0000644000175000017500000000122412050524441033454 0ustar ebourgebourgpackage org.junit.tests.experimental.theories.extendingwithstubs; import java.util.Arrays; public class StringableObject { public Object obj; public StringableObject(Object obj) { this.obj = obj; } public Object stringableObject() { if (isListableArray()) { return Arrays.asList((Object[]) obj); } else { return obj; } } private boolean isListableArray() { Class type = obj.getClass(); return type.isArray() && !type.getComponentType().isPrimitive(); } @Override public String toString() { return stringableObject().toString(); } }././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootjunit4-4.11/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StubbedTheories.javajunit4-4.11/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StubbedTheories.j0000644000175000017500000000451212050524441033503 0ustar ebourgebourgpackage org.junit.tests.experimental.theories.extendingwithstubs; import java.util.ArrayList; import java.util.List; import org.junit.experimental.theories.ParameterSignature; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.internal.Assignments; import org.junit.internal.AssumptionViolatedException; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement; import org.junit.runners.model.TestClass; public class StubbedTheories extends Theories { public StubbedTheories(Class klass) throws InitializationError { super(klass); } @Override public Statement methodBlock(FrameworkMethod method) { return new StubbedTheoryAnchor(method, getTestClass()); } public static class StubbedTheoryAnchor extends TheoryAnchor { public StubbedTheoryAnchor(FrameworkMethod method, TestClass testClass) { super(method, testClass); } private List queues = new ArrayList(); @Override protected void handleAssumptionViolation(AssumptionViolatedException e) { super.handleAssumptionViolation(e); for (GuesserQueue queue : queues) { queue.update(e); } } @Override protected void runWithIncompleteAssignment(Assignments incomplete) throws InstantiationException, IllegalAccessException, Throwable { GuesserQueue guessers = createGuesserQueue(incomplete); queues.add(guessers); while (!guessers.isEmpty()) runWithAssignment(incomplete.assignNext(guessers.remove(0))); queues.remove(guessers); } private GuesserQueue createGuesserQueue(Assignments incomplete) throws InstantiationException, IllegalAccessException { ParameterSignature nextUnassigned = incomplete.nextUnassigned(); if (nextUnassigned.hasAnnotation(Stub.class)) { GuesserQueue queue = new GuesserQueue(); queue.add(new Guesser(nextUnassigned.getType())); return queue; } return GuesserQueue.forSingleValues(incomplete.potentialsForNextUnassigned()); } } } junit4-4.11/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/MethodCall.java0000644000175000017500000000254212050524441033115 0ustar ebourgebourgpackage org.junit.tests.experimental.theories.extendingwithstubs; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MethodCall { private final Method method; private final Object[] args; public MethodCall(Method method, Object... args) { this.method = method; this.args = args; } @Override public boolean equals(Object obj) { MethodCall call = (MethodCall) obj; return call.method.equals(method) && Arrays.deepEquals(call.args, args); } @Override public int hashCode() { return 1; } public Class getReturnType() { return method.getReturnType(); } @Override public String toString() { return String.format("%s(%s)", method.getName(), argListString()); } private String argListString() { if (args == null) { return null; } return argList().toString().substring(1, argList().toString().length() - 1); } private List argList() { ArrayList list = new ArrayList(); for (Object arg : args) { list.add(new StringableObject(arg)); } return list; } public Object stringableObject(Object arg) { return new StringableObject(arg).stringableObject(); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootjunit4-4.11/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Correspondent.javajunit4-4.11/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Correspondent.jav0000644000175000017500000000024112050524441033557 0ustar ebourgebourgpackage org.junit.tests.experimental.theories.extendingwithstubs; public interface Correspondent { String getAnswer(String question, String... bucket); } junit4-4.11/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/GuesserQueue.java0000644000175000017500000000337412050524441033527 0ustar ebourgebourgpackage org.junit.tests.experimental.theories.extendingwithstubs; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.experimental.theories.PotentialAssignment; import org.junit.internal.AssumptionViolatedException; public class GuesserQueue extends ArrayList { static class ReguessableDecorator extends ReguessableValue { private final PotentialAssignment delegate; public ReguessableDecorator(PotentialAssignment delegate) { this.delegate = delegate; } @Override public List reguesses(AssumptionViolatedException e) { return Collections.emptyList(); } @Override public Object getValue() throws CouldNotGenerateValueException { return delegate.getValue(); } @Override public String getDescription() throws CouldNotGenerateValueException { return delegate.getDescription(); } } static GuesserQueue forSingleValues( List potentials) { GuesserQueue returnThis = new GuesserQueue(); for (PotentialAssignment potentialParameterValue : potentials) { returnThis .add(new GuesserQueue.ReguessableDecorator(potentialParameterValue)); } return returnThis; } private static final long serialVersionUID = 1L; private ReguessableValue lastRemoved; public void update(AssumptionViolatedException e) { if (lastRemoved != null) { addAll(lastRemoved.reguesses(e)); } } @Override public ReguessableValue remove(int index) { lastRemoved = super.remove(index); return lastRemoved; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootjunit4-4.11/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/ReguessableValue.javajunit4-4.11/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/ReguessableValue.0000644000175000017500000000066012050524441033474 0ustar ebourgebourgpackage org.junit.tests.experimental.theories.extendingwithstubs; import java.util.List; import org.junit.experimental.theories.PotentialAssignment; import org.junit.internal.AssumptionViolatedException; public abstract class ReguessableValue extends PotentialAssignment { public ReguessableValue() { super(); } public abstract List reguesses( AssumptionViolatedException e); }junit4-4.11/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Stub.java0000644000175000017500000000032712050524441032015 0ustar ebourgebourgpackage org.junit.tests.experimental.theories.extendingwithstubs; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface Stub { } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootjunit4-4.11/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StubbedTheoriesTest.javajunit4-4.11/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/StubbedTheoriesTe0000644000175000017500000000075212050524441033546 0ustar ebourgebourgpackage org.junit.tests.experimental.theories.extendingwithstubs; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assume.assumeThat; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; @RunWith(StubbedTheories.class) public class StubbedTheoriesTest { @Theory public void ask(@Stub Correspondent correspondent) { assumeThat(correspondent.getAnswer("What is five?", "four", "five"), is("five")); } } junit4-4.11/src/test/java/org/junit/tests/experimental/theories/extendingwithstubs/Guesser.java0000644000175000017500000000720312050524441032515 0ustar ebourgebourgpackage org.junit.tests.experimental.theories.extendingwithstubs; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import java.util.Random; import org.hamcrest.BaseDescription; import org.hamcrest.Description; import org.junit.internal.AssumptionViolatedException; public class Guesser extends ReguessableValue { static class GuessMap extends HashMap implements InvocationHandler { private static final long serialVersionUID = 1L; public GuessMap(GuessMap guesses) { super(guesses); } public GuessMap() { } GuessMap replaceGuess(Object oldValue, Object newValue) { GuessMap newGuesses = new GuessMap(this); for (Entry entry : newGuesses.entrySet()) { if (entry.getValue().equals(oldValue)) { entry.setValue(newValue); } } return newGuesses; } protected Object generateGuess(Class returnType) { if (returnType.equals(String.class)) { return "GUESS" + new Random().nextInt(); } if (returnType.equals(Integer.class) || returnType.equals(int.class)) { return new Random().nextInt(); } return null; } Object getGuess(MethodCall call) { if (!containsKey(call)) { put(call, generateGuess(call.getReturnType())); } return get(call); } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return getGuess(new MethodCall(method, args)); } } private final GuessMap guesses; private final Class type; public Guesser(Class type) { this(type, new GuessMap()); } public Guesser(Class type2, GuessMap guesses) { this.type = type2; this.guesses = guesses; } @SuppressWarnings("unchecked") public T getProxy() { return (T) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{getType()}, guesses); } @Override public List reguesses(AssumptionViolatedException e) { final ArrayList returnThis = new ArrayList(); e.describeTo(new BaseDescription() { @Override protected void append(char arg0) { } boolean expectedSeen = false; Object expected = null; @Override public Description appendValue(Object value) { noteValue(value); return super.appendValue(value); } private void noteValue(Object value) { if (!expectedSeen) { expected = value; expectedSeen = true; return; } GuessMap newGuesses = guesses.replaceGuess(expected, value); returnThis.add(new Guesser(getType(), newGuesses)); } }); return returnThis; } @Override public Object getValue() throws CouldNotGenerateValueException { return getProxy(); } public Class getType() { return type; } @Override public String getDescription() throws CouldNotGenerateValueException { return "guesser[" + type + "]"; } }junit4-4.11/src/test/java/org/junit/tests/experimental/theories/runner/0000755000175000017500000000000012050524441025602 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/experimental/theories/runner/WithOnlyTestAnnotations.java0000644000175000017500000000475712050524441033315 0ustar ebourgebourgpackage org.junit.tests.experimental.theories.runner; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.experimental.results.PrintableResult.testResult; import static org.junit.experimental.results.ResultMatchers.failureCountIs; import static org.junit.experimental.results.ResultMatchers.isSuccessful; import org.junit.Test; import org.junit.experimental.theories.DataPoint; import org.junit.experimental.theories.Theories; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.RunWith; public class WithOnlyTestAnnotations { @RunWith(Theories.class) public static class HonorExpectedException { @Test(expected = NullPointerException.class) public void shouldThrow() { } } @Test public void honorExpected() throws Exception { assertThat(testResult(HonorExpectedException.class).failureCount(), is(1)); } @RunWith(Theories.class) public static class HonorExpectedExceptionPasses { @Test(expected = NullPointerException.class) public void shouldThrow() { throw new NullPointerException(); } } @Test public void honorExpectedPassing() throws Exception { assertThat(testResult(HonorExpectedExceptionPasses.class), isSuccessful()); } @RunWith(Theories.class) public static class HonorTimeout { @Test(timeout = 5) public void shouldStop() { while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { } } } } @Test public void honorTimeout() throws Exception { assertThat(testResult(HonorTimeout.class), failureCountIs(1)); } @RunWith(Theories.class) static public class ErrorWhenTestHasParametersDespiteTheories { @DataPoint public static int ZERO = 0; @Test public void testMethod(int i) { } } @Test public void testErrorWhenTestHasParametersDespiteTheories() { JUnitCore core = new JUnitCore(); Result result = core.run(ErrorWhenTestHasParametersDespiteTheories.class); assertEquals(1, result.getFailureCount()); String message = result.getFailures().get(0).getMessage(); assertThat(message, containsString("should have no parameters")); } }././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootjunit4-4.11/src/test/java/org/junit/tests/experimental/theories/runner/UnsuccessfulWithDataPointFields.javajunit4-4.11/src/test/java/org/junit/tests/experimental/theories/runner/UnsuccessfulWithDataPointFiel0000644000175000017500000001061712050524441033454 0ustar ebourgebourgpackage org.junit.tests.experimental.theories.runner; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.experimental.results.PrintableResult.testResult; import static org.junit.experimental.results.ResultMatchers.failureCountIs; import static org.junit.experimental.results.ResultMatchers.hasFailureContaining; import static org.junit.experimental.results.ResultMatchers.hasSingleFailureContaining; import org.hamcrest.CoreMatchers; import org.junit.Test; import org.junit.experimental.results.PrintableResult; import org.junit.experimental.theories.DataPoint; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; import org.junit.runners.model.TestClass; public class UnsuccessfulWithDataPointFields { @RunWith(Theories.class) public static class HasATheory { @DataPoint public static int ONE = 1; @Theory public void everythingIsZero(int x) { assertThat(x, is(0)); } } @Test public void theoryClassMethodsShowUp() throws Exception { assertThat(new Theories(HasATheory.class).getDescription() .getChildren().size(), is(1)); } @Test public void theoryAnnotationsAreRetained() throws Exception { assertThat(new TestClass(HasATheory.class).getAnnotatedMethods( Theory.class).size(), is(1)); } @Test public void canRunTheories() throws Exception { assertThat(testResult(HasATheory.class), hasSingleFailureContaining("Expected")); } @RunWith(Theories.class) public static class DoesntUseParams { @DataPoint public static int ONE = 1; @Theory public void everythingIsZero(int x, int y) { assertThat(2, is(3)); } } @Test public void reportBadParams() throws Exception { assertThat(testResult(DoesntUseParams.class), hasSingleFailureContaining("everythingIsZero(ONE, ONE)")); } @RunWith(Theories.class) public static class NullsOK { @DataPoint public static String NULL = null; @DataPoint public static String A = "A"; @Theory public void everythingIsA(String a) { assertThat(a, is("A")); } } @Test public void nullsUsedUnlessProhibited() throws Exception { assertThat(testResult(NullsOK.class), hasSingleFailureContaining("null")); } @RunWith(Theories.class) public static class DataPointsMustBeStatic { @DataPoint public int THREE = 3; @DataPoint public int FOUR = 4; @Theory public void numbers(int x) { } } @Test public void dataPointsMustBeStatic() { assertThat( testResult(DataPointsMustBeStatic.class), CoreMatchers.both(failureCountIs(2)) .and( hasFailureContaining("DataPoint field THREE must be static")) .and( hasFailureContaining("DataPoint field FOUR must be static"))); } @RunWith(Theories.class) public static class TheoriesMustBePublic { @DataPoint public static int THREE = 3; @Theory void numbers(int x) { } } @Test public void theoriesMustBePublic() { assertThat( testResult(TheoriesMustBePublic.class), hasSingleFailureContaining("public")); } @RunWith(Theories.class) public static class DataPointsMustBePublic { @DataPoint static int THREE = 3; @DataPoint protected static int FOUR = 4; @SuppressWarnings("unused") @DataPoint private static int FIVE = 5; @Theory public void numbers(int x) { } } @Test public void dataPointsMustBePublic() { assertThat( testResult(DataPointsMustBePublic.class), allOf(failureCountIs(3), hasFailureContaining("DataPoint field THREE must be public"), hasFailureContaining("DataPoint field FOUR must be public"), hasFailureContaining("DataPoint field FIVE must be public"))); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootjunit4-4.11/src/test/java/org/junit/tests/experimental/theories/runner/SuccessfulWithDataPointFields.javajunit4-4.11/src/test/java/org/junit/tests/experimental/theories/runner/SuccessfulWithDataPointFields0000644000175000017500000001145412050524441033440 0ustar ebourgebourgpackage org.junit.tests.experimental.theories.runner; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; import java.util.ArrayList; import java.util.List; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.experimental.theories.DataPoint; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; @RunWith(Enclosed.class) public class SuccessfulWithDataPointFields { @RunWith(Theories.class) public static class HasATwoParameterTheory { @DataPoint public static int ONE = 1; @Theory public void allIntsAreEqual(int x, int y) { assertThat(x, is(y)); } } @RunWith(Theories.class) public static class BeforeAndAfterOnSameInstance { @DataPoint public static String A = "A"; private int befores = 0; @Before public void incrementBefore() { befores++; } @Theory public void stringsAreOK(String string) { assertTrue(befores == 1); } } @RunWith(Theories.class) public static class NewObjectEachTime { @DataPoint public static String A = "A"; @DataPoint public static String B = "B"; private List list = new ArrayList(); @Theory public void addToEmptyList(String string) { list.add(string); assertThat(list.size(), is(1)); } } @RunWith(Theories.class) public static class PositiveInts { @DataPoint public static final int ONE = 1; private int x; public PositiveInts(int x) { assumeTrue(x > 0); this.x = x; } @Theory public void haveAPostiveSquare() { assertTrue(x * x > 0); } } @RunWith(Theories.class) public static class PositiveIntsWithNegativeField { @DataPoint public static final int ONE = 1; @DataPoint public static final int NEGONE = -1; private int x; public PositiveIntsWithNegativeField(int x) { assumeTrue(x > 0); this.x = x; } @Theory public void haveAPostiveSquare() { assertTrue(x > 0); } } @RunWith(Theories.class) public static class PositiveIntsWithMethodParams { @DataPoint public static final int ONE = 1; private int x; public PositiveIntsWithMethodParams(int x) { assumeTrue(x > 0); this.x = x; } @Theory public void haveAPostiveSquare(int y) { assumeTrue(y > 0); assertTrue(x * y > 0); } } @RunWith(Theories.class) public static class DifferentTypesInConstructor { @DataPoint public static final int ONE = 1; @DataPoint public static final String A = "A"; public DifferentTypesInConstructor(int x) { } @Theory public void yesIndeed(String a) { } } @RunWith(Theories.class) public static class BeforeAndAfterEachTime { public static int befores = 0; @DataPoint public static String A = "A"; @DataPoint public static String B = "B"; @Before public void incrementBefore() { befores++; } @BeforeClass public static void resetCalls() { befores = 0; } @Theory public void stringsAreOK(String string) { } @AfterClass public static void calledTwice() { assertEquals(2, befores); } } @RunWith(Theories.class) public static class OneTestTwoAnnotations { public static int tests = 0; @DataPoint public static String A = "A"; @BeforeClass public static void resetCalls() { tests = 0; } @Theory @Test public void stringsAreOK(String string) { tests++; } @AfterClass public static void calledTwice() { assertEquals(1, tests); } } @RunWith(Theories.class) static public class StaticPublicNonDataPoints { // DataPoint which passes the test @DataPoint public static int ZERO = 0; // Not annotated as a DataPoint and therefore should be ignored: public static int ONE = 1; @Theory public void onlyAnnotatedFields(int i) { assertTrue(i == 0); } } }././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootjunit4-4.11/src/test/java/org/junit/tests/experimental/theories/runner/TypeMatchingBetweenMultiDataPointsMethod.javajunit4-4.11/src/test/java/org/junit/tests/experimental/theories/runner/TypeMatchingBetweenMultiDataP0000644000175000017500000000330312050524441033357 0ustar ebourgebourgpackage org.junit.tests.experimental.theories.runner; import static org.junit.Assert.assertThat; import static org.junit.experimental.results.PrintableResult.testResult; import static org.junit.experimental.results.ResultMatchers.isSuccessful; import org.junit.Test; import org.junit.experimental.theories.DataPoint; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; public class TypeMatchingBetweenMultiDataPointsMethod { @RunWith(Theories.class) public static class WithWrongfullyTypedDataPointsMethod { @DataPoint public static String[] correctlyTyped = {"Good", "Morning"}; @DataPoints public static String[] wrongfullyTyped() { return new String[]{"Hello", "World"}; } @Theory public void testTheory(String[] array) { } } @Test public void ignoreWrongTypedDataPointsMethod() { assertThat(testResult(WithWrongfullyTypedDataPointsMethod.class), isSuccessful()); } @RunWith(Theories.class) public static class WithCorrectlyTypedDataPointsMethod { @DataPoint public static String[] correctlyTyped = {"Good", "Morning"}; @DataPoints public static String[][] anotherCorrectlyTyped() { return new String[][]{ {"Hello", "World"} }; } @Theory public void testTheory(String[] array) { } } @Test public void pickUpMultiPointDataPointMethods() throws Exception { assertThat(testResult(WithCorrectlyTypedDataPointsMethod.class), isSuccessful()); } } ././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootjunit4-4.11/src/test/java/org/junit/tests/experimental/theories/runner/WithUnresolvedGenericTypeVariablesOnTheoryParms.javajunit4-4.11/src/test/java/org/junit/tests/experimental/theories/runner/WithUnresolvedGenericTypeVari0000644000175000017500000001432412050524441033474 0ustar ebourgebourgpackage org.junit.tests.experimental.theories.runner; import static org.junit.Assert.assertThat; import static org.junit.experimental.results.PrintableResult.testResult; import static org.junit.experimental.results.ResultMatchers.failureCountIs; import static org.junit.experimental.results.ResultMatchers.hasFailureContaining; import static org.junit.experimental.results.ResultMatchers.hasSingleFailureContaining; import static org.junit.experimental.results.ResultMatchers.isSuccessful; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import org.junit.Test; import org.junit.experimental.results.PrintableResult; import org.junit.experimental.theories.DataPoint; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; public class WithUnresolvedGenericTypeVariablesOnTheoryParms { @Test public void whereTypeVariableIsOnTheTheory() { PrintableResult result = testResult(TypeVariableOnTheoryOnly.class); assertThat(result, isSuccessful()); } @RunWith(Theories.class) public static class TypeVariableOnTheoryOnly { @DataPoint public static List strings = Arrays.asList("foo", "bar"); @Theory public void forItems(Collection items) { } } @Test public void whereTypeVariableIsOnTheoryParm() { PrintableResult result = testResult(TypeVariableOnTheoryParm.class); assertThat(result, hasSingleFailureContaining("unresolved type variable T")); } @RunWith(Theories.class) public static class TypeVariableOnTheoryParm { @DataPoint public static String string = "foo"; @Theory public void forItem(T item) { } } @Test public void whereTypeVariableIsOnParameterizedTheoryParm() { PrintableResult result = testResult(TypeVariableOnParameterizedTheoryParm.class); assertThat(result, hasSingleFailureContaining("unresolved type variable T")); } @RunWith(Theories.class) public static class TypeVariableOnParameterizedTheoryParm { @DataPoint public static List strings = Arrays.asList("foo", "bar"); @Theory public void forItems(Collection items) { } } @Test public void whereTypeVariableIsOnWildcardUpperBoundOnTheoryParm() { PrintableResult result = testResult(TypeVariableOnWildcardUpperBoundOnTheoryParm.class); assertThat(result, hasSingleFailureContaining("unresolved type variable U")); } @RunWith(Theories.class) public static class TypeVariableOnWildcardUpperBoundOnTheoryParm { @DataPoint public static List strings = Arrays.asList("foo", "bar"); @Theory public void forItems(Collection items) { } } @Test public void whereTypeVariableIsOnWildcardLowerBoundOnTheoryParm() { PrintableResult result = testResult(TypeVariableOnWildcardLowerBoundOnTheoryParm.class); assertThat(result, hasSingleFailureContaining("unresolved type variable V")); } @RunWith(Theories.class) public static class TypeVariableOnWildcardLowerBoundOnTheoryParm { @DataPoint public static List strings = Arrays.asList("foo", "bar"); @Theory public void forItems(Collection items) { } } @Test public void whereTypeVariableIsOnArrayTypeOnTheoryParm() { PrintableResult result = testResult(TypeVariableOnArrayTypeOnTheoryParm.class); assertThat(result, hasSingleFailureContaining("unresolved type variable T")); } @RunWith(Theories.class) public static class TypeVariableOnArrayTypeOnTheoryParm { @DataPoints public static String[][] items() { return new String[][]{new String[]{"foo"}, new String[]{"bar"}}; } @Theory public void forItems(T[] items) { } } @Test public void whereTypeVariableIsOnComponentOfArrayTypeOnTheoryParm() { PrintableResult result = testResult(TypeVariableOnComponentOfArrayTypeOnTheoryParm.class); assertThat(result, hasSingleFailureContaining("unresolved type variable U")); } @RunWith(Theories.class) public static class TypeVariableOnComponentOfArrayTypeOnTheoryParm { @DataPoints public static List[][] items() { return new List[][]{ new List[]{Arrays.asList("foo")}, new List[]{Arrays.asList("bar")} }; } @Theory public void forItems(Collection[] items) { } } @Test public void whereTypeVariableIsOnTheoryClass() { PrintableResult result = testResult(TypeVariableOnTheoryClass.class); assertThat(result, hasSingleFailureContaining("unresolved type variable T")); } @RunWith(Theories.class) public static class TypeVariableOnTheoryClass { @DataPoint public static String item = "bar"; @Theory public void forItem(T item) { } } @Test public void whereTypeVariablesAbound() { PrintableResult result = testResult(TypeVariablesAbound.class); assertThat(result, failureCountIs(7)); assertThat(result, hasFailureContaining("unresolved type variable A")); assertThat(result, hasFailureContaining("unresolved type variable B")); assertThat(result, hasFailureContaining("unresolved type variable C")); assertThat(result, hasFailureContaining("unresolved type variable D")); assertThat(result, hasFailureContaining("unresolved type variable E")); assertThat(result, hasFailureContaining("unresolved type variable F")); assertThat(result, hasFailureContaining("unresolved type variable G")); } @RunWith(Theories.class) public static class TypeVariablesAbound> { @Theory public void forItem(A first, Collection second, Map third, List fourth, F[] fifth, Collection[] sixth) { } } }junit4-4.11/src/test/java/org/junit/tests/experimental/theories/runner/TheoriesPerformanceTest.java0000644000175000017500000000244512050524441033256 0ustar ebourgebourgpackage org.junit.tests.experimental.theories.runner; import static org.junit.Assert.assertThat; import static org.junit.Assume.assumeTrue; import static org.junit.experimental.results.PrintableResult.testResult; import static org.junit.experimental.results.ResultMatchers.isSuccessful; import org.junit.Test; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; public class TheoriesPerformanceTest { @RunWith(Theories.class) public static class UpToTen { @DataPoints public static int[] ints = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; @Theory public void threeInts(int x, int y, int z) { // pass always } } private static final boolean TESTING_PERFORMANCE = false; // If we do not share the same instance of TestClass, repeatedly parsing the // class's annotations looking for @Befores and @Afters gets really costly. // // Likewise, the TestClass must be passed into AllMembersSupplier, or the // annotation parsing is again costly. @Test public void tryCombinationsQuickly() { assumeTrue(TESTING_PERFORMANCE); assertThat(testResult(UpToTen.class), isSuccessful()); } } junit4-4.11/src/test/java/org/junit/tests/experimental/theories/runner/WhenNoParametersMatch.java0000644000175000017500000000310012050524441032636 0ustar ebourgebourgpackage org.junit.tests.experimental.theories.runner; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; import static org.junit.Assume.assumeThat; import static org.junit.experimental.results.PrintableResult.testResult; import org.hamcrest.Matcher; import org.junit.experimental.theories.DataPoint; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; @RunWith(Theories.class) public class WhenNoParametersMatch { @DataPoints public static int[] ints = {0, 1, 3, 5, 1776}; @DataPoints public static Matcher[] matchers = {not(0), is(1)}; @RunWith(Theories.class) public static class AssumptionsFail { @DataPoint public static int DATA = 0; @DataPoint public static Matcher MATCHER = null; @Theory public void nonZeroIntsAreFun(int x) { assumeThat(x, MATCHER); } } @Theory public void showFailedAssumptionsWhenNoParametersFound(int data, Matcher matcher) throws Exception { assumeThat(data, not(matcher)); AssumptionsFail.DATA = data; AssumptionsFail.MATCHER = matcher; String result = testResult(AssumptionsFail.class).toString(); assertThat(result, containsString(matcher.toString())); assertThat(result, containsString("" + data)); } }junit4-4.11/src/test/java/org/junit/tests/experimental/theories/runner/WithDataPointMethod.java0000644000175000017500000000776512050524441032344 0ustar ebourgebourgpackage org.junit.tests.experimental.theories.runner; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.everyItem; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import static org.junit.experimental.results.PrintableResult.testResult; import static org.junit.experimental.results.ResultMatchers.isSuccessful; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.hamcrest.Matcher; import org.junit.Test; import org.junit.experimental.theories.DataPoint; import org.junit.experimental.theories.PotentialAssignment; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.experimental.theories.internal.Assignments; import org.junit.runner.JUnitCore; import org.junit.runner.RunWith; import org.junit.runner.notification.Failure; import org.junit.runners.model.TestClass; public class WithDataPointMethod { @RunWith(Theories.class) public static class HasDataPointMethod { @DataPoint public static int oneHundred() { return 100; } @Theory public void allIntsOk(int x) { } } @RunWith(Theories.class) public static class HasUglyDataPointMethod { @DataPoint public static int oneHundred() { return 100; } @DataPoint public static int oneUglyHundred() { throw new RuntimeException(); } @Theory public void allIntsOk(int x) { } } @Test public void pickUpDataPointMethods() { assertThat(testResult(HasDataPointMethod.class), isSuccessful()); } @Test public void ignoreExceptionsFromDataPointMethods() { assertThat(testResult(HasUglyDataPointMethod.class), isSuccessful()); } @RunWith(Theories.class) public static class DataPointMethodReturnsMutableObject { @DataPoint public static List empty() { return new ArrayList(); } @DataPoint public static int ONE = 1; @DataPoint public static int TWO = 2; @Theory public void everythingsEmpty(List first, int number) { assertThat(first.size(), is(0)); first.add("a"); } } @Test public void mutableObjectsAreCreatedAfresh() { assertThat(failures(DataPointMethodReturnsMutableObject.class), empty()); } @RunWith(Theories.class) public static class HasDateMethod { @DataPoint public int oneHundred() { return 100; } public Date notADataPoint() { return new Date(); } @Theory public void allIntsOk(int x) { } @Theory public void onlyStringsOk(String s) { } @Theory public void onlyDatesOk(Date d) { } } @Test public void ignoreDataPointMethodsWithWrongTypes() throws Exception { assertThat(potentialValues( HasDateMethod.class.getMethod("onlyStringsOk", String.class)) .toString(), not(containsString("100"))); } @Test public void ignoreDataPointMethodsWithoutAnnotation() throws Throwable { assertThat(potentialValues( HasDateMethod.class.getMethod("onlyDatesOk", Date.class)) .size(), is(0)); } private List potentialValues(Method method) throws Exception { return Assignments.allUnassigned(method, new TestClass(HasDateMethod.class)) .potentialsForNextUnassigned(); } private List failures(Class type) { return JUnitCore.runClasses(type).getFailures(); } private Matcher> empty() { return everyItem(nullValue(Failure.class)); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootjunit4-4.11/src/test/java/org/junit/tests/experimental/theories/runner/WithExtendedParameterSources.javajunit4-4.11/src/test/java/org/junit/tests/experimental/theories/runner/WithExtendedParameterSources.0000644000175000017500000001006312050524441033404 0ustar ebourgebourgpackage org.junit.tests.experimental.theories.runner; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import static org.junit.experimental.results.PrintableResult.testResult; import static org.junit.experimental.results.ResultMatchers.isSuccessful; import org.junit.Test; import org.junit.experimental.results.ResultMatchers; import org.junit.experimental.theories.DataPoint; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.experimental.theories.suppliers.TestedOn; import org.junit.runner.JUnitCore; import org.junit.runner.RunWith; public class WithExtendedParameterSources { @RunWith(Theories.class) public static class ParameterAnnotations { @Theory public void everythingIsOne(@TestedOn(ints = {1}) int number) { assertThat(number, is(1)); } } @Test public void testedOnLimitsParameters() throws Exception { assertThat(testResult(ParameterAnnotations.class), ResultMatchers .isSuccessful()); } @RunWith(Theories.class) public static class ShouldFilterNull { @DataPoint public static String NULL = null; @DataPoint public static String A = "a"; @Theory(nullsAccepted = false) public void allStringsAreNonNull(String s) { assertThat(s, notNullValue()); } } @Test public void shouldFilterNull() { assertThat(testResult(ShouldFilterNull.class), isSuccessful()); } @RunWith(Theories.class) public static class DataPointArrays { public static String log = ""; @DataPoints public static String[] STRINGS = new String[]{"A", "B"}; @Theory public void addToLog(String string) { log += string; } } @Test public void getDataPointsFromArray() { DataPointArrays.log = ""; JUnitCore.runClasses(DataPointArrays.class); assertThat(DataPointArrays.log, is("AB")); } @RunWith(Theories.class) public static class DataPointArrayMethod { public static String log = ""; @DataPoints public static String[] STRINGS() { return new String[]{"A", "B"}; } ; @Theory public void addToLog(String string) { log += string; } } @Test public void getDataPointsFromArrayMethod() { DataPointArrayMethod.log = ""; JUnitCore.runClasses(DataPointArrayMethod.class); assertThat(DataPointArrayMethod.log, is("AB")); } @RunWith(Theories.class) public static class DataPointMalformedArrayMethods { public static String log = ""; @DataPoints public static String[] STRINGS() { return new String[]{"A", "B"}; } ; @DataPoints public static String STRING() { return "C"; } @DataPoints public static int[] INTS() { return new int[]{1, 2, 3}; } @Theory public void addToLog(String string) { log += string; } } @Test public void getDataPointsFromArrayMethodInSpiteOfMalformedness() { DataPointArrayMethod.log = ""; JUnitCore.runClasses(DataPointArrayMethod.class); assertThat(DataPointArrayMethod.log, is("AB")); } @RunWith(Theories.class) public static class DataPointArrayToBeUsedForWholeParameter { public static String log = ""; @DataPoint public static String[] STRINGS = new String[]{"A", "B"}; @Theory public void addToLog(String[] strings) { log += strings[0]; } } @Test public void dataPointCanBeArray() { DataPointArrayToBeUsedForWholeParameter.log = ""; JUnitCore.runClasses(DataPointArrayToBeUsedForWholeParameter.class); assertThat(DataPointArrayToBeUsedForWholeParameter.log, is("A")); } }junit4-4.11/src/test/java/org/junit/tests/experimental/theories/ParameterizedAssertionErrorTest.java0000644000175000017500000000530012050524441033470 0ustar ebourgebourgpackage org.junit.tests.experimental.theories; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; import static org.junit.Assume.assumeThat; import org.junit.Test; import org.junit.experimental.theories.DataPoint; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.experimental.theories.internal.ParameterizedAssertionError; import org.junit.runner.RunWith; @RunWith(Theories.class) public class ParameterizedAssertionErrorTest { @DataPoint public static final String METHOD_NAME = "methodName"; @DataPoint public static final NullPointerException NULL_POINTER_EXCEPTION = new NullPointerException(); @DataPoint public static Object[] NO_OBJECTS = new Object[0]; @DataPoint public static ParameterizedAssertionError A = new ParameterizedAssertionError( NULL_POINTER_EXCEPTION, METHOD_NAME); @DataPoint public static ParameterizedAssertionError B = new ParameterizedAssertionError( NULL_POINTER_EXCEPTION, METHOD_NAME); @DataPoint public static ParameterizedAssertionError B2 = new ParameterizedAssertionError( NULL_POINTER_EXCEPTION, "methodName2"); @Theory public void equalParameterizedAssertionErrorsHaveSameToString( ParameterizedAssertionError a, ParameterizedAssertionError b) { assumeThat(a, is(b)); assertThat(a.toString(), is(b.toString())); } @Theory public void differentParameterizedAssertionErrorsHaveDifferentToStrings( ParameterizedAssertionError a, ParameterizedAssertionError b) { assumeThat(a, not(b)); assertThat(a.toString(), not(b.toString())); } @Theory public void equalsReturnsTrue(Throwable targetException, String methodName, Object[] params) { assertThat(new ParameterizedAssertionError(targetException, methodName, params), is(new ParameterizedAssertionError(targetException, methodName, params))); } @Theory(nullsAccepted = false) public void buildParameterizedAssertionError(String methodName, String param) { assertThat(new ParameterizedAssertionError(new RuntimeException(), methodName, param).toString(), containsString(methodName)); } @Test public void canJoinWhenToStringFails() { assertThat(ParameterizedAssertionError.join(" ", new Object() { @Override public String toString() { throw new UnsupportedOperationException(); } }), is("[toString failed]")); } } junit4-4.11/src/test/java/org/junit/tests/experimental/theories/ParameterSignatureTest.java0000644000175000017500000000342512050524441031602 0ustar ebourgebourgpackage org.junit.tests.experimental.theories; import static org.hamcrest.CoreMatchers.isA; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assume.assumeTrue; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.List; import org.hamcrest.CoreMatchers; import org.junit.Test; import org.junit.experimental.theories.DataPoint; import org.junit.experimental.theories.ParameterSignature; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.experimental.theories.suppliers.TestedOn; import org.junit.runner.RunWith; @RunWith(Theories.class) public class ParameterSignatureTest { @DataPoint public static Method getType() throws SecurityException, NoSuchMethodException { return ParameterSignatureTest.class.getMethod("getType", Method.class, int.class); } @DataPoint public static int ZERO = 0; @DataPoint public static int ONE = 1; @Theory public void getType(Method method, int index) { assumeTrue(index < method.getParameterTypes().length); assertEquals(method.getParameterTypes()[index], ParameterSignature .signatures(method).get(index).getType()); } public void foo(@TestedOn(ints = {1, 2, 3}) int x) { } @Test public void getAnnotations() throws SecurityException, NoSuchMethodException { Method method = ParameterSignatureTest.class.getMethod("foo", int.class); List annotations = ParameterSignature.signatures(method) .get(0).getAnnotations(); assertThat(annotations, CoreMatchers.hasItem(isA(TestedOn.class))); } } junit4-4.11/src/test/java/org/junit/tests/experimental/MatcherTest.java0000644000175000017500000000300512050524441025533 0ustar ebourgebourgpackage org.junit.tests.experimental; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; import static org.junit.Assume.assumeThat; import static org.junit.experimental.results.ResultMatchers.hasFailureContaining; import static org.junit.experimental.results.ResultMatchers.hasSingleFailureContaining; import java.util.Arrays; import org.hamcrest.Matcher; import org.junit.experimental.results.PrintableResult; import org.junit.experimental.theories.DataPoint; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.Description; import org.junit.runner.RunWith; import org.junit.runner.notification.Failure; @RunWith(Theories.class) public class MatcherTest { @DataPoint public static Matcher SINGLE_FAILURE = hasSingleFailureContaining("cheese"); @DataPoint public static Matcher ANY_FAILURE = hasFailureContaining("cheese"); @DataPoint public static PrintableResult TWO_FAILURES_ONE_CHEESE = new PrintableResult( Arrays.asList(failure("cheese"), failure("mustard"))); @Theory public void differentMatchersHaveDifferentDescriptions( Matcher matcher1, Matcher matcher2, T value) { assumeThat(value, matcher1); assumeThat(value, not(matcher2)); assertThat(matcher1.toString(), not(matcher2.toString())); } private static Failure failure(String string) { return new Failure(Description.EMPTY, new Error(string)); } } junit4-4.11/src/test/java/org/junit/tests/experimental/categories/0000755000175000017500000000000012050524441024574 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/experimental/categories/CategoryTest.java0000644000175000017500000001624712050524441030066 0ustar ebourgebourgpackage org.junit.tests.experimental.categories; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.experimental.results.PrintableResult.testResult; import static org.junit.experimental.results.ResultMatchers.isSuccessful; import org.junit.Test; import org.junit.experimental.categories.Categories; import org.junit.experimental.categories.Categories.CategoryFilter; import org.junit.experimental.categories.Categories.ExcludeCategory; import org.junit.experimental.categories.Categories.IncludeCategory; import org.junit.experimental.categories.Category; import org.junit.runner.JUnitCore; import org.junit.runner.Request; import org.junit.runner.Result; import org.junit.runner.RunWith; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import org.junit.runners.model.InitializationError; public class CategoryTest { public interface FastTests { // category marker } public interface SlowTests { // category marker } public static class A { @Test public void a() { fail(); } @Category(SlowTests.class) @Test public void b() { } } @Category(SlowTests.class) public static class B { @Test public void c() { } } public static class C { @Test public void d() { fail(); } } @RunWith(Categories.class) @IncludeCategory(SlowTests.class) @SuiteClasses({A.class, B.class, C.class}) public static class SlowTestSuite { } @RunWith(Categories.class) @IncludeCategory(SlowTests.class) @SuiteClasses({A.class}) public static class JustA { } @Test public void testCountOnJustA() { assertThat(testResult(JustA.class), isSuccessful()); } @Test public void testCount() { assertThat(testResult(SlowTestSuite.class), isSuccessful()); } public static class Category1 { } public static class Category2 { } public static class SomeAreSlow { @Test public void noCategory() { } @Category(Category1.class) @Test public void justCategory1() { } @Category(Category2.class) @Test public void justCategory2() { } @Category({Category1.class, Category2.class}) @Test public void both() { } @Category({Category2.class, Category1.class}) @Test public void bothReversed() { } } @RunWith(Categories.class) @ExcludeCategory(Category1.class) @SuiteClasses({SomeAreSlow.class}) public static class SomeAreSlowSuite { } @Test public void testCountOnAWithoutSlowTests() { Result result = JUnitCore.runClasses(SomeAreSlowSuite.class); assertEquals(2, result.getRunCount()); assertTrue(result.wasSuccessful()); } @RunWith(Categories.class) @ExcludeCategory(Category1.class) @IncludeCategory(Category2.class) @SuiteClasses({SomeAreSlow.class}) public static class IncludeAndExcludeSuite { } @Test public void testsThatAreBothIncludedAndExcludedAreExcluded() { Result result = JUnitCore.runClasses(IncludeAndExcludeSuite.class); assertEquals(1, result.getRunCount()); assertTrue(result.wasSuccessful()); } @RunWith(Suite.class) @SuiteClasses({A.class, B.class, C.class}) public static class TestSuiteWithNoCategories { } @Test public void testCountWithExplicitFilter() throws Throwable { CategoryFilter include = CategoryFilter.include(SlowTests.class); Request baseRequest = Request.aClass(TestSuiteWithNoCategories.class); Result result = new JUnitCore().run(baseRequest.filterWith(include)); assertTrue(result.wasSuccessful()); assertEquals(2, result.getRunCount()); } @Test public void categoryFilterLeavesOnlyMatchingMethods() throws InitializationError, NoTestsRemainException { CategoryFilter filter = CategoryFilter.include(SlowTests.class); BlockJUnit4ClassRunner runner = new BlockJUnit4ClassRunner(A.class); filter.apply(runner); assertEquals(1, runner.testCount()); } public static class OneFastOneSlow { @Category(FastTests.class) @Test public void a() { } @Category(SlowTests.class) @Test public void b() { } } @Test public void categoryFilterRejectsIncompatibleCategory() throws InitializationError, NoTestsRemainException { CategoryFilter filter = CategoryFilter.include(SlowTests.class); BlockJUnit4ClassRunner runner = new BlockJUnit4ClassRunner( OneFastOneSlow.class); filter.apply(runner); assertEquals(1, runner.testCount()); } public static class OneFast { @Category(FastTests.class) @Test public void a() { } } @RunWith(Categories.class) @IncludeCategory(SlowTests.class) @SuiteClasses({OneFast.class}) public static class OneFastSuite { } @Test public void ifNoTestsToRunUseErrorRunner() { Result result = JUnitCore.runClasses(OneFastSuite.class); assertEquals(1, result.getRunCount()); assertEquals(1, result.getFailureCount()); } @Test public void describeACategoryFilter() { CategoryFilter filter = CategoryFilter.include(SlowTests.class); assertEquals("category " + SlowTests.class, filter.describe()); } public static class OneThatIsBothFastAndSlow { @Category({FastTests.class, SlowTests.class}) @Test public void a() { } } @RunWith(Categories.class) @IncludeCategory(SlowTests.class) @SuiteClasses({OneThatIsBothFastAndSlow.class}) public static class ChooseSlowFromBoth { } @Test public void runMethodWithTwoCategories() { assertThat(testResult(ChooseSlowFromBoth.class), isSuccessful()); } public interface VerySlowTests extends SlowTests { } public static class OneVerySlowTest { @Category(VerySlowTests.class) @Test public void a() { } } @RunWith(Categories.class) @IncludeCategory(SlowTests.class) @SuiteClasses({OneVerySlowTest.class}) public static class RunSlowFromVerySlow { } @Test public void subclassesOfIncludedCategoriesAreRun() { assertThat(testResult(RunSlowFromVerySlow.class), isSuccessful()); } public static class ClassAsCategory { } public static class OneMoreTest { @Category(ClassAsCategory.class) @Test public void a() { } } @RunWith(Categories.class) @IncludeCategory(ClassAsCategory.class) @SuiteClasses({OneMoreTest.class}) public static class RunClassAsCategory { } @Test public void classesCanBeCategories() { assertThat(testResult(RunClassAsCategory.class), isSuccessful()); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootjunit4-4.11/src/test/java/org/junit/tests/experimental/categories/CategoriesAndParameterizedTest.javajunit4-4.11/src/test/java/org/junit/tests/experimental/categories/CategoriesAndParameterizedTest.jav0000644000175000017500000000756612050524441033401 0ustar ebourgebourgpackage org.junit.tests.experimental.categories; import static org.junit.Assert.assertThat; import static org.junit.experimental.results.PrintableResult.testResult; import static org.junit.experimental.results.ResultMatchers.hasFailureContaining; import static org.junit.experimental.results.ResultMatchers.isSuccessful; import java.util.Collection; import java.util.Collections; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Categories; import org.junit.experimental.categories.Categories.IncludeCategory; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.junit.runners.Suite.SuiteClasses; public class CategoriesAndParameterizedTest { public static class Token { } @RunWith(Parameterized.class) public static class WellBehavedParameterizedTest { public WellBehavedParameterizedTest(String a) { } @Parameters public static Collection getParameters() { return Collections.singletonList(new Object[]{"a"}); } @Test public void testSomething() { Assert.assertTrue(true); } } @RunWith(Parameterized.class) public static class ParameterizedTestWithAttemptedMethodCategory { public ParameterizedTestWithAttemptedMethodCategory(String a) { } @Parameters public static Collection getParameters() { return Collections.singletonList(new Object[]{"a"}); } @Test @Category(Token.class) public void testSomething() { Assert.assertTrue(true); } } @RunWith(Parameterized.class) @Category(Token.class) public static class ParameterizedTestWithClassCategory { public ParameterizedTestWithClassCategory(String a) { } @Parameters public static Collection getParameters() { return Collections.singletonList(new Object[]{"a"}); } @Test public void testSomething() { Assert.assertTrue(true); } } @Category(Token.class) public static class VanillaCategorizedJUnitTest { @Test public void testSomething() { Assert.assertTrue(true); } } @RunWith(Categories.class) @IncludeCategory(Token.class) @SuiteClasses({VanillaCategorizedJUnitTest.class, WellBehavedParameterizedTest.class, ParameterizedTestWithClassCategory.class}) public static class ParameterTokenSuiteWellFormed { } @RunWith(Categories.class) @IncludeCategory(Token.class) @SuiteClasses({ParameterizedTestWithAttemptedMethodCategory.class, VanillaCategorizedJUnitTest.class}) public static class ParameterTokenSuiteMalformed { } @RunWith(Categories.class) @IncludeCategory(Token.class) @SuiteClasses({VanillaCategorizedJUnitTest.class, ParameterizedTestWithAttemptedMethodCategory.class}) public static class ParameterTokenSuiteMalformedAndSwapped { } @Test public void shouldSucceedWithAParameterizedClassSomewhere() { assertThat(testResult(ParameterTokenSuiteWellFormed.class), isSuccessful()); } @Test public void shouldFailWithMethodLevelCategoryAnnotation() { assertThat( testResult(ParameterTokenSuiteMalformed.class), hasFailureContaining("Category annotations on Parameterized classes are not supported on individual methods.")); } @Test public void shouldFailWithMethodLevelCategoryAnnotationSwapped() { assertThat( testResult(ParameterTokenSuiteMalformedAndSwapped.class), hasFailureContaining("Category annotations on Parameterized classes are not supported on individual methods.")); } }junit4-4.11/src/test/java/org/junit/tests/experimental/parallel/0000755000175000017500000000000012050524441024243 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/experimental/parallel/ParallelClassTest.java0000644000175000017500000000512712050524441030475 0ustar ebourgebourgpackage org.junit.tests.experimental.parallel; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNot.not; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Test; import org.junit.experimental.ParallelComputer; import org.junit.runner.JUnitCore; import org.junit.runner.Result; public class ParallelClassTest { private static final long TIMEOUT = 15; private static volatile Thread fExample1One = null; private static volatile Thread fExample1Two = null; private static volatile Thread fExample2One = null; private static volatile Thread fExample2Two = null; private static volatile CountDownLatch fSynchronizer; public static class Example1 { @Test public void one() throws InterruptedException { fSynchronizer.countDown(); assertTrue(fSynchronizer.await(TIMEOUT, TimeUnit.SECONDS)); fExample1One = Thread.currentThread(); } @Test public void two() throws InterruptedException { fSynchronizer.countDown(); assertTrue(fSynchronizer.await(TIMEOUT, TimeUnit.SECONDS)); fExample1Two = Thread.currentThread(); } } public static class Example2 { @Test public void one() throws InterruptedException { fSynchronizer.countDown(); assertTrue(fSynchronizer.await(TIMEOUT, TimeUnit.SECONDS)); fExample2One = Thread.currentThread(); } @Test public void two() throws InterruptedException { fSynchronizer.countDown(); assertTrue(fSynchronizer.await(TIMEOUT, TimeUnit.SECONDS)); fExample2Two = Thread.currentThread(); } } @Before public void init() { fExample1One = null; fExample1Two = null; fExample2One = null; fExample2Two = null; fSynchronizer = new CountDownLatch(2); } @Test public void testsRunInParallel() { Result result = JUnitCore.runClasses(ParallelComputer.classes(), Example1.class, Example2.class); assertTrue(result.wasSuccessful()); assertNotNull(fExample1One); assertNotNull(fExample1Two); assertNotNull(fExample2One); assertNotNull(fExample2Two); assertThat(fExample1One, is(fExample1Two)); assertThat(fExample2One, is(fExample2Two)); assertThat(fExample1One, is(not(fExample2One))); } } junit4-4.11/src/test/java/org/junit/tests/experimental/parallel/ParallelMethodTest.java0000644000175000017500000000336612050524441030653 0ustar ebourgebourgpackage org.junit.tests.experimental.parallel; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNot.not; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.ParallelComputer; import org.junit.runner.JUnitCore; import org.junit.runner.Result; public class ParallelMethodTest { private static final long TIMEOUT = 15; private static volatile Thread fOne = null; private static volatile Thread fTwo = null; public static class Example { private static volatile CountDownLatch fSynchronizer; @BeforeClass public static void init() { fSynchronizer = new CountDownLatch(2); } @Test public void one() throws InterruptedException { fSynchronizer.countDown(); assertTrue(fSynchronizer.await(TIMEOUT, TimeUnit.SECONDS)); fOne = Thread.currentThread(); } @Test public void two() throws InterruptedException { fSynchronizer.countDown(); assertTrue(fSynchronizer.await(TIMEOUT, TimeUnit.SECONDS)); fTwo = Thread.currentThread(); } } @Before public void init() { fOne = null; fTwo = null; } @Test public void testsRunInParallel() { Result result = JUnitCore.runClasses(ParallelComputer.methods(), Example.class); assertTrue(result.wasSuccessful()); assertNotNull(fOne); assertNotNull(fTwo); assertThat(fOne, is(not(fTwo))); } } junit4-4.11/src/test/java/org/junit/tests/experimental/AssumptionTest.java0000644000175000017500000001714012050524441026317 0ustar ebourgebourgpackage org.junit.tests.experimental; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; 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.assumeNoException; import static org.junit.Assume.assumeNotNull; import static org.junit.Assume.assumeThat; import static org.junit.Assume.assumeTrue; import static org.junit.experimental.results.PrintableResult.testResult; import static org.junit.experimental.results.ResultMatchers.isSuccessful; import java.util.ArrayList; import java.util.List; import org.junit.Assume; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.internal.AssumptionViolatedException; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; public class AssumptionTest { public static class HasFailingAssumption { @Test public void assumptionsFail() { assumeThat(3, is(4)); fail(); } } @Test public void failedAssumptionsMeanPassing() { Result result = JUnitCore.runClasses(HasFailingAssumption.class); assertThat(result.getRunCount(), is(1)); assertThat(result.getIgnoreCount(), is(0)); assertThat(result.getFailureCount(), is(0)); } private static int assumptionFailures = 0; @Test public void failedAssumptionsCanBeDetectedByListeners() { assumptionFailures = 0; JUnitCore core = new JUnitCore(); core.addListener(new RunListener() { @Override public void testAssumptionFailure(Failure failure) { assumptionFailures++; } }); core.run(HasFailingAssumption.class); assertThat(assumptionFailures, is(1)); } public static class HasPassingAssumption { @Test public void assumptionsFail() { assumeThat(3, is(3)); fail(); } } @Test public void passingAssumptionsScootThrough() { Result result = JUnitCore.runClasses(HasPassingAssumption.class); assertThat(result.getRunCount(), is(1)); assertThat(result.getIgnoreCount(), is(0)); assertThat(result.getFailureCount(), is(1)); } @Test(expected = AssumptionViolatedException.class) public void assumeThatWorks() { assumeThat(1, is(2)); } @Test public void assumeThatPasses() { assumeThat(1, is(1)); assertCompletesNormally(); } @Test public void assumeThatPassesOnStrings() { assumeThat("x", is("x")); assertCompletesNormally(); } @Test(expected = AssumptionViolatedException.class) public void assumeNotNullThrowsException() { Object[] objects = {1, 2, null}; assumeNotNull(objects); } @Test public void assumeNotNullPasses() { Object[] objects = {1, 2}; assumeNotNull(objects); assertCompletesNormally(); } @Test public void assumeNotNullIncludesParameterList() { try { Object[] objects = {1, 2, null}; assumeNotNull(objects); } catch (AssumptionViolatedException e) { assertThat(e.getMessage(), containsString("1, 2, null")); } catch (Exception e) { fail("Should have thrown AssumptionViolatedException"); } } @Test public void assumeNoExceptionThrows() { final Throwable exception = new NullPointerException(); try { assumeNoException(exception); fail("Should have thrown exception"); } catch (AssumptionViolatedException e) { assertThat(e.getCause(), is(exception)); } } private void assertCompletesNormally() { } @Test(expected = AssumptionViolatedException.class) public void assumeTrueWorks() { Assume.assumeTrue(false); } public static class HasFailingAssumeInBefore { @Before public void checkForSomethingThatIsntThere() { assumeTrue(false); } @Test public void failing() { fail(); } } @Test public void failingAssumptionInBeforePreventsTestRun() { assertThat(testResult(HasFailingAssumeInBefore.class), isSuccessful()); } public static class HasFailingAssumeInBeforeClass { @BeforeClass public static void checkForSomethingThatIsntThere() { assumeTrue(false); } @Test public void failing() { fail(); } } @Test public void failingAssumptionInBeforeClassIgnoresClass() { assertThat(testResult(HasFailingAssumeInBeforeClass.class), isSuccessful()); } public static class AssumptionFailureInConstructor { public AssumptionFailureInConstructor() { assumeTrue(false); } @Test public void shouldFail() { fail(); } } @Test public void failingAssumptionInConstructorIgnoresClass() { assertThat(testResult(AssumptionFailureInConstructor.class), isSuccessful()); } @Test(expected = IllegalArgumentException.class) public void assumeWithExpectedException() { assumeTrue(false); } final static String message = "Some random message string."; final static Throwable t = new Throwable(); /** * @see AssumptionTest#assumptionsWithMessage() */ public static class HasAssumeWithMessage { @Test public void testMethod() { assumeTrue(message, false); } } @Test public void assumptionsWithMessage() { final List failures = runAndGetAssumptionFailures(HasAssumeWithMessage.class); assertTrue(failures.get(0).getMessage().contains(message)); } /** * @see AssumptionTest#assumptionsWithMessageAndCause() */ public static class HasAssumeWithMessageAndCause { @Test public void testMethod() { assumeNoException(message, t); } } @Test public void assumptionsWithMessageAndCause() { final List failures = runAndGetAssumptionFailures(HasAssumeWithMessageAndCause.class); assertTrue(failures.get(0).getMessage().contains(message)); assertSame(failures.get(0).getException().getCause(), t); } public static class HasFailingAssumptionWithMessage { @Test public void assumptionsFail() { assumeThat(message, 3, is(4)); fail(); } } @Test public void failedAssumptionsWithMessage() { final List failures = runAndGetAssumptionFailures(HasFailingAssumptionWithMessage.class); assertEquals(failures.size(), 1); assertTrue(failures.get(0).getMessage().contains(message)); } /** * Helper method that runs tests on clazz and returns any * {@link Failure} objects that were {@link AssumptionViolatedException}s. */ private static List runAndGetAssumptionFailures(Class clazz) { final List failures = new ArrayList(); final JUnitCore core = new JUnitCore(); core.addListener(new RunListener() { @Override public void testAssumptionFailure(Failure failure) { failures.add(failure); } }); core.run(clazz); return failures; } } junit4-4.11/src/test/java/org/junit/tests/manipulation/0000755000175000017500000000000012050524441022452 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/manipulation/FilterableTest.java0000644000175000017500000000316212050524441026230 0ustar ebourgebourgpackage org.junit.tests.manipulation; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.RunWith; import org.junit.runner.manipulation.Filter; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; public class FilterableTest { public static class FilteredRunner extends Parameterized { public FilteredRunner(Class klass) throws Throwable { super(klass); filter(new Filter() { @Override public boolean shouldRun(Description description) { return !description.getDisplayName().contains("skip"); } @Override public String describe() { return "skip methods containing the word 'skip'"; } }); } } @RunWith(FilteredRunner.class) public static class FilteredTest { @Parameters public static List parameters() { return Arrays.asList(new Object[]{3}, new Object[]{4}); } public FilteredTest(int x) { } @Test public void skipThis() { Assert.fail(); } @Test public void runThis() { } } @Test public void testFilterInRunnerConstructor() { Result result = JUnitCore.runClasses(FilteredTest.class); assertTrue(result.wasSuccessful()); } } junit4-4.11/src/test/java/org/junit/tests/manipulation/FilterTest.java0000644000175000017500000000242512050524441025405 0ustar ebourgebourgpackage org.junit.tests.manipulation; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.manipulation.Filter; public class FilterTest { public static class NamedFilter extends Filter { private final String fName; public NamedFilter(String name) { fName = name; } @Override public boolean shouldRun(Description description) { return false; } @Override public String describe() { return fName; } } @Test public void intersectionText() { NamedFilter a = new NamedFilter("a"); NamedFilter b = new NamedFilter("b"); assertEquals("a and b", a.intersect(b).describe()); assertEquals("b and a", b.intersect(a).describe()); } @Test public void intersectSelf() { NamedFilter a = new NamedFilter("a"); assertSame(a, a.intersect(a)); } @Test public void intersectAll() { NamedFilter a = new NamedFilter("a"); assertSame(a, a.intersect(Filter.ALL)); assertSame(a, Filter.ALL.intersect(a)); assertSame(Filter.ALL, Filter.ALL.intersect(Filter.ALL)); } } junit4-4.11/src/test/java/org/junit/tests/manipulation/SortableTest.java0000644000175000017500000001235612050524441025737 0ustar ebourgebourgpackage org.junit.tests.manipulation; import static org.junit.Assert.assertEquals; import java.util.Comparator; import junit.framework.JUnit4TestAdapter; import org.junit.Before; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.Request; import org.junit.runner.RunWith; import org.junit.runner.Runner; import org.junit.runner.notification.RunNotifier; @RunWith(Enclosed.class) public class SortableTest { private static Comparator forward() { return new Comparator() { public int compare(Description o1, Description o2) { return o1.getDisplayName().compareTo(o2.getDisplayName()); } }; } private static Comparator backward() { return new Comparator() { public int compare(Description o1, Description o2) { return o2.getDisplayName().compareTo(o1.getDisplayName()); } }; } public static class TestClassRunnerIsSortable { private static String log = ""; public static class SortMe { @Test public void a() { log += "a"; } @Test public void b() { log += "b"; } @Test public void c() { log += "c"; } } @Before public void resetLog() { log = ""; } @Test public void sortingForwardWorksOnTestClassRunner() { Request forward = Request.aClass(SortMe.class).sortWith(forward()); new JUnitCore().run(forward); assertEquals("abc", log); } @Test public void sortingBackwardWorksOnTestClassRunner() { Request backward = Request.aClass(SortMe.class).sortWith(backward()); new JUnitCore().run(backward); assertEquals("cba", log); } @RunWith(Enclosed.class) public static class Enclosing { public static class A { @Test public void a() { log += "Aa"; } @Test public void b() { log += "Ab"; } @Test public void c() { log += "Ac"; } } public static class B { @Test public void a() { log += "Ba"; } @Test public void b() { log += "Bb"; } @Test public void c() { log += "Bc"; } } } @Test public void sortingForwardWorksOnSuite() { Request forward = Request.aClass(Enclosing.class).sortWith(forward()); new JUnitCore().run(forward); assertEquals("AaAbAcBaBbBc", log); } @Test public void sortingBackwardWorksOnSuite() { Request backward = Request.aClass(Enclosing.class).sortWith(backward()); new JUnitCore().run(backward); assertEquals("BcBbBaAcAbAa", log); } } public static class TestClassRunnerIsSortableWithSuiteMethod { private static String log = ""; public static class SortMe { @Test public void a() { log += "a"; } @Test public void b() { log += "b"; } @Test public void c() { log += "c"; } public static junit.framework.Test suite() { return new JUnit4TestAdapter(SortMe.class); } } @Before public void resetLog() { log = ""; } @Test public void sortingForwardWorksOnTestClassRunner() { Request forward = Request.aClass(SortMe.class).sortWith(forward()); new JUnitCore().run(forward); assertEquals("abc", log); } @Test public void sortingBackwardWorksOnTestClassRunner() { Request backward = Request.aClass(SortMe.class).sortWith(backward()); new JUnitCore().run(backward); assertEquals("cba", log); } } public static class UnsortableRunnersAreHandledWithoutCrashing { public static class UnsortableRunner extends Runner { public UnsortableRunner(Class klass) { } @Override public Description getDescription() { return Description.EMPTY; } @Override public void run(RunNotifier notifier) { } } @RunWith(UnsortableRunner.class) public static class Unsortable { @Test public void a() { } } @Test public void unsortablesAreHandledWithoutCrashing() { Request unsorted = Request.aClass(Unsortable.class).sortWith(forward()); new JUnitCore().run(unsorted); } } } junit4-4.11/src/test/java/org/junit/tests/manipulation/SingleMethodTest.java0000644000175000017500000001161612050524441026544 0ustar ebourgebourgpackage org.junit.tests.manipulation; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import java.util.Arrays; import java.util.List; import junit.framework.JUnit4TestAdapter; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.Request; import org.junit.runner.Result; import org.junit.runner.RunWith; import org.junit.runner.Runner; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.Filterable; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; public class SingleMethodTest { public static int count; static public class OneTimeSetup { @BeforeClass public static void once() { count++; } @Test public void one() { } @Test public void two() { } } @Test public void oneTimeSetup() throws Exception { count = 0; Runner runner = Request.method(OneTimeSetup.class, "one").getRunner(); Result result = new JUnitCore().run(runner); assertEquals(1, count); assertEquals(1, result.getRunCount()); } @RunWith(Parameterized.class) static public class ParameterizedOneTimeSetup { @Parameters public static List params() { return Arrays.asList(new Object[]{1}, new Object[]{2}); } public ParameterizedOneTimeSetup(int x) { } @Test public void one() { } } @Test public void parameterizedFilterToSingleMethod() throws Exception { count = 0; Runner runner = Request.method(ParameterizedOneTimeSetup.class, "one[0]").getRunner(); Result result = new JUnitCore().run(runner); assertEquals(1, result.getRunCount()); } @RunWith(Parameterized.class) static public class ParameterizedOneTimeBeforeClass { @Parameters public static List params() { return Arrays.asList(new Object[]{1}, new Object[]{2}); } public ParameterizedOneTimeBeforeClass(int x) { } @BeforeClass public static void once() { count++; } @Test public void one() { } } @Test public void parameterizedBeforeClass() throws Exception { count = 0; JUnitCore.runClasses(ParameterizedOneTimeBeforeClass.class); assertEquals(1, count); } @Test public void filteringAffectsPlan() throws Exception { Runner runner = Request.method(OneTimeSetup.class, "one").getRunner(); assertEquals(1, runner.testCount()); } @Test public void nonexistentMethodCreatesFailure() throws Exception { assertEquals(1, new JUnitCore().run( Request.method(OneTimeSetup.class, "thisMethodDontExist")) .getFailureCount()); } @Test(expected = NoTestsRemainException.class) public void filteringAwayEverythingThrowsException() throws NoTestsRemainException { Filterable runner = (Filterable) Request.aClass(OneTimeSetup.class).getRunner(); runner.filter(new Filter() { @Override public boolean shouldRun(Description description) { return false; } @Override public String describe() { return null; } }); } public static class TestOne { @Test public void a() { } @Test public void b() { } } public static class TestTwo { @Test public void a() { } @Test public void b() { } } @RunWith(Suite.class) @SuiteClasses({TestOne.class, TestTwo.class}) public static class OneTwoSuite { } @Test public void eliminateUnnecessaryTreeBranches() throws Exception { Runner runner = Request.aClass(OneTwoSuite.class).filterWith( Description.createTestDescription(TestOne.class, "a")) .getRunner(); Description description = runner.getDescription(); assertEquals(1, description.getChildren().size()); } public static class HasSuiteMethod { @Test public void a() { } @Test public void b() { } public static junit.framework.Test suite() { return new JUnit4TestAdapter(HasSuiteMethod.class); } } @Test public void classesWithSuiteMethodsAreFiltered() { int testCount = Request.method(HasSuiteMethod.class, "a").getRunner().getDescription().testCount(); assertThat(testCount, is(1)); } }junit4-4.11/src/test/java/org/junit/tests/internal/0000755000175000017500000000000012050524441021566 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/internal/runners/0000755000175000017500000000000012050524441023262 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/internal/runners/statements/0000755000175000017500000000000012050524441025451 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/internal/runners/statements/FailOnTimeoutTest.java0000644000175000017500000001371212050524441031677 0ustar ebourgebourgpackage org.junit.tests.internal.runners.statements; import static java.lang.Long.MAX_VALUE; import static java.lang.Math.atan; import static java.lang.System.currentTimeMillis; import static java.lang.Thread.sleep; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Rule; import org.junit.Test; import org.junit.internal.runners.statements.FailOnTimeout; import org.junit.rules.ExpectedException; import org.junit.runners.model.Statement; /** * @author Asaf Ary, Stefan Birkner */ public class FailOnTimeoutTest { private static final int TIMEOUT = 100; @Rule public final ExpectedException thrown = ExpectedException.none(); private final TestStatement statement = new TestStatement(); private final FailOnTimeout failOnTimeout = new FailOnTimeout(statement, TIMEOUT); @Test public void throwExceptionWithNiceMessageOnTimeout() throws Throwable { thrown.expectMessage("test timed out after 100 milliseconds"); evaluateWithWaitDuration(TIMEOUT + 50); } @Test public void sendUpExceptionThrownByStatement() throws Throwable { RuntimeException exception = new RuntimeException(); thrown.expect(is(exception)); evaluateWithException(exception); } @Test public void throwExceptionIfTheSecondCallToEvaluateNeedsTooMuchTime() throws Throwable { thrown.expect(Exception.class); evaluateWithWaitDuration(0); evaluateWithWaitDuration(TIMEOUT + 50); } @Test public void throwTimeoutExceptionOnSecondCallAlthoughFirstCallThrowsException() throws Throwable { thrown.expectMessage("test timed out after 100 milliseconds"); try { evaluateWithException(new RuntimeException()); } catch (Throwable expected) { } evaluateWithWaitDuration(TIMEOUT + 50); } private void evaluateWithException(Exception exception) throws Throwable { statement.nextException = exception; statement.waitDuration = 0; failOnTimeout.evaluate(); } private void evaluateWithWaitDuration(int waitDuration) throws Throwable { statement.nextException = null; statement.waitDuration = waitDuration; failOnTimeout.evaluate(); } private static final class TestStatement extends Statement { int waitDuration; Exception nextException; @Override public void evaluate() throws Throwable { sleep(waitDuration); if (nextException != null) { throw nextException; } } } @Test public void stopEndlessStatement() throws Throwable { InfiniteLoopStatement infiniteLoop = new InfiniteLoopStatement(); FailOnTimeout infiniteLoopTimeout = new FailOnTimeout(infiniteLoop, TIMEOUT); try { infiniteLoopTimeout.evaluate(); } catch (Exception timeoutException) { sleep(20); // time to interrupt the thread int firstCount = InfiniteLoopStatement.COUNT; sleep(20); // time to increment the count assertTrue("Thread has not been stopped.", firstCount == InfiniteLoopStatement.COUNT); } } private static final class InfiniteLoopStatement extends Statement { private static int COUNT = 0; @Override public void evaluate() throws Throwable { while (true) { sleep(10); // sleep in order to enable interrupting thread ++COUNT; } } } @Test public void stackTraceContainsRealCauseOfTimeout() throws Throwable { StuckStatement stuck = new StuckStatement(); FailOnTimeout stuckTimeout = new FailOnTimeout(stuck, TIMEOUT); try { stuckTimeout.evaluate(); // We must not get here, we expect a timeout exception fail("Expected timeout exception"); } catch (Exception timeoutException) { StackTraceElement[] stackTrace = timeoutException.getStackTrace(); boolean stackTraceContainsTheRealCauseOfTheTimeout = false; boolean stackTraceContainsOtherThanTheRealCauseOfTheTimeout = false; for (StackTraceElement element : stackTrace) { String methodName = element.getMethodName(); if ("theRealCauseOfTheTimeout".equals(methodName)) { stackTraceContainsTheRealCauseOfTheTimeout = true; } if ("notTheRealCauseOfTheTimeout".equals(methodName)) { stackTraceContainsOtherThanTheRealCauseOfTheTimeout = true; } } assertTrue( "Stack trace does not contain the real cause of the timeout", stackTraceContainsTheRealCauseOfTheTimeout); assertFalse( "Stack trace contains other than the real cause of the timeout, which can be very misleading", stackTraceContainsOtherThanTheRealCauseOfTheTimeout); } } private static final class StuckStatement extends Statement { @Override public void evaluate() throws Throwable { try { // Must show up in stack trace theRealCauseOfTheTimeout(); } catch (InterruptedException e) { } finally { // Must _not_ show up in stack trace notTheRealCauseOfTheTimeout(); } } private void theRealCauseOfTheTimeout() throws InterruptedException { sleep(MAX_VALUE); } private void notTheRealCauseOfTheTimeout() { for (long now = currentTimeMillis(), eta = now + 1000L; now < eta; now = currentTimeMillis()) { // Doesn't matter, just pretend to be busy atan(now); } } } }junit4-4.11/src/test/java/org/junit/tests/listening/0000755000175000017500000000000012050524441021746 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/listening/RunnerTest.java0000644000175000017500000000344012050524441024723 0ustar ebourgebourgpackage org.junit.tests.listening; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import junit.framework.TestCase; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.notification.RunListener; public class RunnerTest { private boolean wasRun; public class MyListener extends RunListener { int testCount; @Override public void testRunStarted(Description description) { this.testCount = description.testCount(); } } public static class Example { @Test public void empty() { } } @Test public void newTestCount() { JUnitCore runner = new JUnitCore(); MyListener listener = new MyListener(); runner.addListener(listener); runner.run(Example.class); assertEquals(1, listener.testCount); } public static class ExampleTest extends TestCase { public void testEmpty() { } } @Test public void oldTestCount() { JUnitCore runner = new JUnitCore(); MyListener listener = new MyListener(); runner.addListener(listener); runner.run(ExampleTest.class); assertEquals(1, listener.testCount); } public static class NewExample { @Test public void empty() { } } @Test public void testFinished() { JUnitCore runner = new JUnitCore(); wasRun = false; RunListener listener = new MyListener() { @Override public void testFinished(Description description) { wasRun = true; } }; runner.addListener(listener); runner.run(NewExample.class); assertTrue(wasRun); } } junit4-4.11/src/test/java/org/junit/tests/listening/ListenerTest.java0000644000175000017500000000200012050524441025226 0ustar ebourgebourgpackage org.junit.tests.listening; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.notification.RunListener; public class ListenerTest { static private String log; public static class OneTest { @Test public void nothing() { } } @Test public void notifyListenersInTheOrderInWhichTheyAreAdded() { JUnitCore core = new JUnitCore(); log = ""; core.addListener(new RunListener() { @Override public void testRunStarted(Description description) throws Exception { log += "first "; } }); core.addListener(new RunListener() { @Override public void testRunStarted(Description description) throws Exception { log += "second "; } }); core.run(OneTest.class); assertEquals("first second ", log); } } junit4-4.11/src/test/java/org/junit/tests/listening/UserStopTest.java0000644000175000017500000000146112050524441025237 0ustar ebourgebourgpackage org.junit.tests.listening; import org.junit.Before; import org.junit.Test; import org.junit.runner.Request; import org.junit.runner.notification.RunNotifier; import org.junit.runner.notification.StoppedByUserException; public class UserStopTest { private RunNotifier fNotifier; @Before public void createNotifier() { fNotifier = new RunNotifier(); fNotifier.pleaseStop(); } @Test(expected = StoppedByUserException.class) public void userStop() { fNotifier.fireTestStarted(null); } public static class OneTest { @Test public void foo() { } } @Test(expected = StoppedByUserException.class) public void stopClassRunner() throws Exception { Request.aClass(OneTest.class).getRunner().run(fNotifier); } } junit4-4.11/src/test/java/org/junit/tests/listening/TestListenerTest.java0000644000175000017500000000340512050524441026100 0ustar ebourgebourgpackage org.junit.tests.listening; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; public class TestListenerTest { int count; class ErrorListener extends RunListener { @Override public void testRunStarted(Description description) throws Exception { throw new Error(); } } public static class OneTest { @Test public void nothing() { } } @Test(expected = Error.class) public void failingListener() { JUnitCore runner = new JUnitCore(); runner.addListener(new ErrorListener()); runner.run(OneTest.class); } class ExceptionListener extends ErrorListener { @Override public void testRunStarted(Description description) throws Exception { count++; throw new Exception(); } } @Test public void reportsFailureOfListener() { JUnitCore core = new JUnitCore(); core.addListener(new ExceptionListener()); count = 0; Result result = core.run(OneTest.class); assertEquals(1, count); assertEquals(1, result.getFailureCount()); Failure testFailure = result.getFailures().get(0); assertEquals(Description.TEST_MECHANISM, testFailure.getDescription()); } @Test public void freshResultEachTime() { JUnitCore core = new JUnitCore(); Result first = core.run(OneTest.class); Result second = core.run(OneTest.class); assertNotSame(first, second); } } junit4-4.11/src/test/java/org/junit/tests/listening/TextListenerTest.java0000644000175000017500000000421212050524441026102 0ustar ebourgebourgpackage org.junit.tests.listening; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.StringContains.containsString; import static org.junit.Assert.assertThat; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.io.PrintStream; import junit.framework.TestCase; import org.junit.Test; import org.junit.internal.TextListener; import org.junit.runner.JUnitCore; import org.junit.tests.TestSystem; public class TextListenerTest extends TestCase { private JUnitCore runner; private OutputStream results; @Override public void setUp() { runner = new JUnitCore(); TestSystem system = new TestSystem(); results = system.outContents(); runner.addListener(new TextListener(system)); } public static class OneTest { @Test public void one() { } } public void testSuccess() throws Exception { runner.run(OneTest.class); assertTrue(results.toString().startsWith(convert(".\nTime: "))); assertTrue(results.toString().endsWith(convert("\n\nOK (1 test)\n\n"))); } public static class ErrorTest { @Test public void error() throws Exception { throw new Exception(); } } public void testError() throws Exception { runner.run(ErrorTest.class); assertTrue(results.toString().startsWith(convert(".E\nTime: "))); assertTrue(results.toString().indexOf(convert("\nThere was 1 failure:\n1) error(org.junit.tests.listening.TextListenerTest$ErrorTest)\njava.lang.Exception")) != -1); } public static class Time { @Test public void time() { } } public void testTime() { runner.run(Time.class); assertThat(results.toString(), containsString("Time: ")); assertThat(results.toString(), not(containsString(convert("Time: \n")))); } private String convert(String string) { OutputStream resultsStream = new ByteArrayOutputStream(); PrintStream writer = new PrintStream(resultsStream); writer.println(); return string.replace("\n", resultsStream.toString()); } } junit4-4.11/src/test/java/org/junit/tests/description/0000755000175000017500000000000012050524441022275 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/description/TestDescriptionTest.java0000644000175000017500000000143312050524441027124 0ustar ebourgebourgpackage org.junit.tests.description; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.junit.runner.Description; public class TestDescriptionTest { @Test public void equalsIsFalseForNonTestDescription() { assertFalse(Description.createTestDescription(getClass(), "a").equals(new Integer(5))); } @Test public void equalsIsTrueForSameNameAndNoExplicitUniqueId() { assertTrue(Description.createSuiteDescription("Hello").equals(Description.createSuiteDescription("Hello"))); } @Test public void equalsIsFalseForSameNameAndDifferentUniqueId() { assertFalse(Description.createSuiteDescription("Hello", 2).equals(Description.createSuiteDescription("Hello", 3))); } }junit4-4.11/src/test/java/org/junit/tests/description/AnnotatedDescriptionTest.java0000644000175000017500000000502212050524441030120 0ustar ebourgebourgpackage org.junit.tests.description; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.lang.annotation.Annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.Request; public class AnnotatedDescriptionTest { @Retention(RetentionPolicy.RUNTIME) public @interface MyOwnAnnotation { } @MyOwnAnnotation public static class AnnotatedClass { @Test public void a() { } } @Test public void annotationsExistOnDescriptionsOfClasses() { assertTrue((describe(AnnotatedClass.class).getAnnotation( MyOwnAnnotation.class) != null)); } @Test public void getAnnotationsReturnsAllAnnotations() { assertEquals(1, describe(ValueAnnotatedClass.class).getAnnotations() .size()); } @Ignore public static class IgnoredClass { @Test public void a() { } } @Test public void annotationsExistOnDescriptionsOfIgnoredClass() { assertTrue((describe(IgnoredClass.class).getAnnotation(Ignore.class) != null)); } @Retention(RetentionPolicy.RUNTIME) public @interface ValuedAnnotation { String value(); } @ValuedAnnotation("hello") public static class ValueAnnotatedClass { @Test public void a() { } } @Test public void descriptionOfTestClassHasValuedAnnotation() { Description description = describe(ValueAnnotatedClass.class); assertEquals("hello", description.getAnnotation(ValuedAnnotation.class) .value()); } @Test public void childlessCopyOfDescriptionStillHasAnnotations() { Description description = describe(ValueAnnotatedClass.class); assertEquals("hello", description.childlessCopy().getAnnotation(ValuedAnnotation.class) .value()); } @Test public void characterizeCreatingMyOwnAnnotation() { Annotation annotation = new Ignore() { public String value() { return "message"; } public Class annotationType() { return Ignore.class; } }; assertEquals(Ignore.class, annotation.annotationType()); } private Description describe(Class testClass) { return Request.aClass(testClass).getRunner().getDescription(); } } junit4-4.11/src/test/java/org/junit/tests/description/SuiteDescriptionTest.java0000644000175000017500000000257312050524441027304 0ustar ebourgebourgpackage org.junit.tests.description; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import org.junit.Test; import org.junit.runner.Description; public class SuiteDescriptionTest { Description childless = Description.createSuiteDescription("a"); Description anotherChildless = Description.createSuiteDescription("a"); Description namedB = Description.createSuiteDescription("b"); Description twoKids = descriptionWithTwoKids("foo", "bar"); Description anotherTwoKids = descriptionWithTwoKids("foo", "baz"); @Test public void equalsIsCorrect() { assertEquals(childless, anotherChildless); assertFalse(childless.equals(namedB)); assertEquals(childless, twoKids); assertEquals(twoKids, anotherTwoKids); assertFalse(twoKids.equals(new Integer(5))); } @Test public void hashCodeIsReasonable() { assertEquals(childless.hashCode(), anotherChildless.hashCode()); assertFalse(childless.hashCode() == namedB.hashCode()); } private Description descriptionWithTwoKids(String first, String second) { Description twoKids = Description.createSuiteDescription("a"); twoKids.addChild(Description.createTestDescription(getClass(), first)); twoKids.addChild(Description.createTestDescription(getClass(), second)); return twoKids; } } junit4-4.11/src/test/java/org/junit/tests/ObjectContractTest.java0000644000175000017500000000245312050524441024365 0ustar ebourgebourgpackage org.junit.tests; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assume.assumeNotNull; import static org.junit.Assume.assumeThat; import java.lang.reflect.Method; import org.junit.Test; import org.junit.Test.None; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; import org.junit.runners.model.FrameworkMethod; @RunWith(Theories.class) public class ObjectContractTest { @DataPoints public static Object[] objects = {new FrameworkMethod(toStringMethod()), new FrameworkMethod(toStringMethod()), 3, null}; @Theory @Test(expected = None.class) public void equalsThrowsNoException(Object a, Object b) { assumeNotNull(a); a.equals(b); } @Theory public void equalsMeansEqualHashCodes(Object a, Object b) { assumeNotNull(a, b); assumeThat(a, is(b)); assertThat(a.hashCode(), is(b.hashCode())); } private static Method toStringMethod() { try { return Object.class.getMethod("toString"); } catch (SecurityException e) { } catch (NoSuchMethodException e) { } return null; } } junit4-4.11/src/test/java/org/junit/tests/validation/0000755000175000017500000000000012050524441022104 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/validation/ValidationTest.java0000644000175000017500000000204712050524441025704 0ustar ebourgebourgpackage org.junit.tests.validation; import static org.junit.Assert.assertEquals; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.JUnitCore; import org.junit.runner.Request; import org.junit.runner.Result; public class ValidationTest { public static class WrongBeforeClass { @BeforeClass protected int a() { return 0; } } @Test public void initializationErrorIsOnCorrectClass() { assertEquals(WrongBeforeClass.class.getName(), Request.aClass(WrongBeforeClass.class).getRunner().getDescription().getDisplayName()); } public static class NonStaticBeforeClass { @BeforeClass public void before() { } @Test public void hereBecauseEveryTestClassNeedsATest() { } } @Test public void nonStaticBeforeClass() { Result result = JUnitCore.runClasses(NonStaticBeforeClass.class); assertEquals("Method before() should be static", result.getFailures().get(0).getMessage()); } } junit4-4.11/src/test/java/org/junit/tests/validation/anotherpackage/0000755000175000017500000000000012050524441025060 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/validation/anotherpackage/Sub.java0000644000175000017500000000013012050524441026446 0ustar ebourgebourgpackage org.junit.tests.validation.anotherpackage; public class Sub extends Super { } junit4-4.11/src/test/java/org/junit/tests/validation/anotherpackage/Super.java0000644000175000017500000000020212050524441027013 0ustar ebourgebourgpackage org.junit.tests.validation.anotherpackage; import org.junit.Test; class Super { @Test public void a() { } } junit4-4.11/src/test/java/org/junit/tests/validation/BadlyFormedClassesTest.java0000644000175000017500000000357112050524441027323 0ustar ebourgebourgpackage org.junit.tests.validation; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.junit.internal.runners.JUnit4ClassRunner; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.RunWith; import org.junit.runner.notification.Failure; @SuppressWarnings("deprecation") public class BadlyFormedClassesTest { public static class FaultyConstructor { public FaultyConstructor() throws Exception { throw new Exception("Thrown during construction"); } @Test public void someTest() { /* * Empty test just to fool JUnit and IDEs into running this class as * a JUnit test */ } } ; @RunWith(JUnit4ClassRunner.class) public static class BadBeforeMethodWithLegacyRunner { @Before void before() { } @Test public void someTest() { } } ; public static class NoTests { // class without tests } @Test public void constructorException() { String message = exceptionMessageFrom(FaultyConstructor.class); assertEquals("Thrown during construction", message); } @Test public void noRunnableMethods() { assertEquals("No runnable methods", exceptionMessageFrom(NoTests.class)); } @Test public void badBeforeMethodWithLegacyRunner() { assertEquals("Method before should be public", exceptionMessageFrom(BadBeforeMethodWithLegacyRunner.class)); } private String exceptionMessageFrom(Class testClass) { JUnitCore core = new JUnitCore(); Result result = core.run(testClass); Failure failure = result.getFailures().get(0); String message = failure.getException().getMessage(); return message; } } junit4-4.11/src/test/java/org/junit/tests/validation/FailedConstructionTest.java0000644000175000017500000000145212050524441027410 0ustar ebourgebourgpackage org.junit.tests.validation; import org.junit.Assert; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class FailedConstructionTest { public static class CantConstruct { public CantConstruct() { throw new RuntimeException(); } @Test public void foo() { } } @Test public void failedConstructionIsTestFailure() { Result result = JUnitCore.runClasses(CantConstruct.class); Failure failure = result.getFailures().get(0); Description expected = Description.createTestDescription(CantConstruct.class, "foo"); Assert.assertEquals(expected, failure.getDescription()); } } junit4-4.11/src/test/java/org/junit/tests/validation/InaccessibleBaseClassTest.java0000644000175000017500000000070112050524441027752 0ustar ebourgebourgpackage org.junit.tests.validation; import org.junit.Test; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.InitializationError; import org.junit.tests.validation.anotherpackage.Sub; public class InaccessibleBaseClassTest { @Test(expected = InitializationError.class) public void inaccessibleBaseClassIsCaughtAtValidation() throws InitializationError { new BlockJUnit4ClassRunner(Sub.class); } } junit4-4.11/src/test/java/org/junit/tests/running/0000755000175000017500000000000012050524441021432 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/running/methods/0000755000175000017500000000000012050524441023075 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/running/methods/InheritedTestTest.java0000644000175000017500000000166312050524441027361 0ustar ebourgebourgpackage org.junit.tests.running.methods; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Before; import org.junit.Test; import org.junit.runner.JUnitCore; import org.junit.runner.Result; public class InheritedTestTest { public abstract static class Super { @Test public void nothing() { } } public static class Sub extends Super { } @Test public void subclassWithOnlyInheritedTestsRuns() { Result result = JUnitCore.runClasses(Sub.class); assertTrue(result.wasSuccessful()); } public static class SubWithBefore extends Super { @Before public void gack() { fail(); } } @Test public void subclassWithInheritedTestAndOwnBeforeRunsBefore() { assertFalse(JUnitCore.runClasses(SubWithBefore.class).wasSuccessful()); } } junit4-4.11/src/test/java/org/junit/tests/running/methods/TestMethodTest.java0000644000175000017500000001263112050524441026663 0ustar ebourgebourgpackage org.junit.tests.running.methods; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Collections; import java.util.List; import junit.framework.JUnit4TestAdapter; import junit.framework.TestResult; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.InitializationError; public class TestMethodTest { @SuppressWarnings("all") public static class EverythingWrong { private EverythingWrong() { } @BeforeClass public void notStaticBC() { } @BeforeClass static void notPublicBC() { } @BeforeClass public static int nonVoidBC() { return 0; } @BeforeClass public static void argumentsBC(int i) { } @BeforeClass public static void fineBC() { } @AfterClass public void notStaticAC() { } @AfterClass static void notPublicAC() { } @AfterClass public static int nonVoidAC() { return 0; } @AfterClass public static void argumentsAC(int i) { } @AfterClass public static void fineAC() { } @After public static void staticA() { } @After void notPublicA() { } @After public int nonVoidA() { return 0; } @After public void argumentsA(int i) { } @After public void fineA() { } @Before public static void staticB() { } @Before void notPublicB() { } @Before public int nonVoidB() { return 0; } @Before public void argumentsB(int i) { } @Before public void fineB() { } @Test public static void staticT() { } @Test void notPublicT() { } @Test public int nonVoidT() { return 0; } @Test public void argumentsT(int i) { } @Test public void fineT() { } } @Test public void testFailures() throws Exception { List problems = validateAllMethods(EverythingWrong.class); int errorCount = 1 + 4 * 5; // missing constructor plus four invalid methods for each annotation */ assertEquals(errorCount, problems.size()); } static public class SuperWrong { @Test void notPublic() { } } static public class SubWrong extends SuperWrong { @Test public void justFine() { } } @Test public void validateInheritedMethods() throws Exception { List problems = validateAllMethods(SubWrong.class); assertEquals(1, problems.size()); } static public class SubShadows extends SuperWrong { @Override @Test public void notPublic() { } } @Test public void dontValidateShadowedMethods() throws Exception { List problems = validateAllMethods(SubShadows.class); assertTrue(problems.isEmpty()); } private List validateAllMethods(Class clazz) { try { new BlockJUnit4ClassRunner(clazz); } catch (InitializationError e) { return e.getCauses(); } return Collections.emptyList(); } static public class IgnoredTest { @Test public void valid() { } @Ignore @Test public void ignored() { } @Ignore("For testing purposes") @Test public void withReason() { } } @Test public void ignoreRunner() { JUnitCore runner = new JUnitCore(); Result result = runner.run(IgnoredTest.class); assertEquals(2, result.getIgnoreCount()); assertEquals(1, result.getRunCount()); } @Test public void compatibility() { TestResult result = new TestResult(); new JUnit4TestAdapter(IgnoredTest.class).run(result); assertEquals(1, result.runCount()); } public static class Confused { @Test public void a(Object b) { } @Test public void a() { } } @Test(expected = InitializationError.class) public void overloaded() throws InitializationError { new BlockJUnit4ClassRunner(Confused.class); } public static class ConstructorParameter { public ConstructorParameter(Object something) { } @Test public void a() { } } @Test(expected = InitializationError.class) public void constructorParameter() throws InitializationError { new BlockJUnit4ClassRunner(ConstructorParameter.class); } public static class OnlyTestIsIgnored { @Ignore @Test public void ignored() { } } @Test public void onlyIgnoredMethodsIsStillFineTestClass() { Result result = JUnitCore.runClasses(OnlyTestIsIgnored.class); assertEquals(0, result.getFailureCount()); assertEquals(1, result.getIgnoreCount()); } } junit4-4.11/src/test/java/org/junit/tests/running/methods/AnnotationTest.java0000644000175000017500000003651212050524441026721 0ustar ebourgebourgpackage org.junit.tests.running.methods; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertThat; import java.util.Collection; import java.util.HashSet; import junit.framework.TestCase; import junit.framework.TestSuite; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; public class AnnotationTest extends TestCase { static boolean run; @Override public void setUp() { run = false; } static public class SimpleTest { @Test public void success() { run = true; } } public void testAnnotatedMethod() throws Exception { JUnitCore runner = new JUnitCore(); runner.run(SimpleTest.class); assertTrue(run); } @RunWith(JUnit4.class) static public class SimpleTestWithFutureProofExplicitRunner { @Test public void success() { run = true; } } public void testAnnotatedMethodWithFutureProofExplicitRunner() throws Exception { JUnitCore runner = new JUnitCore(); runner.run(SimpleTestWithFutureProofExplicitRunner.class); assertTrue(run); } static public class SetupTest { @Before public void before() { run = true; } @Test public void success() { } } public void testSetup() throws Exception { JUnitCore runner = new JUnitCore(); runner.run(SetupTest.class); assertTrue(run); } static public class TeardownTest { @After public void after() { run = true; } @Test public void success() { } } public void testTeardown() throws Exception { JUnitCore runner = new JUnitCore(); runner.run(TeardownTest.class); assertTrue(run); } static public class FailureTest { @Test public void error() throws Exception { org.junit.Assert.fail(); } } public void testRunFailure() throws Exception { JUnitCore runner = new JUnitCore(); Result result = runner.run(FailureTest.class); assertEquals(1, result.getRunCount()); assertEquals(1, result.getFailureCount()); assertEquals(AssertionError.class, result.getFailures().get(0).getException().getClass()); } static public class SetupFailureTest { @Before public void before() { throw new Error(); } @Test public void test() { run = true; } } public void testSetupFailure() throws Exception { JUnitCore core = new JUnitCore(); Result runner = core.run(SetupFailureTest.class); assertEquals(1, runner.getRunCount()); assertEquals(1, runner.getFailureCount()); assertEquals(Error.class, runner.getFailures().get(0).getException().getClass()); assertFalse(run); } static public class TeardownFailureTest { @After public void after() { throw new Error(); } @Test public void test() { } } public void testTeardownFailure() throws Exception { JUnitCore core = new JUnitCore(); Result runner = core.run(TeardownFailureTest.class); assertEquals(1, runner.getRunCount()); assertEquals(1, runner.getFailureCount()); assertEquals(Error.class, runner.getFailures().get(0).getException().getClass()); } static public class TestAndTeardownFailureTest { @After public void after() { throw new Error("hereAfter"); } @Test public void test() throws Exception { throw new Exception("inTest"); } } public void testTestAndTeardownFailure() throws Exception { JUnitCore core = new JUnitCore(); Result runner = core.run(TestAndTeardownFailureTest.class); assertEquals(1, runner.getRunCount()); assertEquals(2, runner.getFailureCount()); assertThat(runner.getFailures().toString(), allOf(containsString("hereAfter"), containsString("inTest"))); } static public class TeardownAfterFailureTest { @After public void after() { run = true; } @Test public void test() throws Exception { throw new Exception(); } } public void testTeardownAfterFailure() throws Exception { JUnitCore runner = new JUnitCore(); runner.run(TeardownAfterFailureTest.class); assertTrue(run); } static int count; static Collection tests; static public class TwoTests { @Test public void one() { count++; tests.add(this); } @Test public void two() { count++; tests.add(this); } } public void testTwoTests() throws Exception { count = 0; tests = new HashSet(); JUnitCore runner = new JUnitCore(); runner.run(TwoTests.class); assertEquals(2, count); assertEquals(2, tests.size()); } static public class OldTest extends TestCase { public void test() { run = true; } } public void testOldTest() throws Exception { JUnitCore runner = new JUnitCore(); runner.run(OldTest.class); assertTrue(run); } static public class OldSuiteTest extends TestCase { public void testOne() { run = true; } } public void testOldSuiteTest() throws Exception { TestSuite suite = new TestSuite(OldSuiteTest.class); JUnitCore runner = new JUnitCore(); runner.run(suite); assertTrue(run); } static public class ExceptionTest { @Test(expected = Error.class) public void expectedException() { throw new Error(); } } public void testException() throws Exception { JUnitCore core = new JUnitCore(); Result result = core.run(ExceptionTest.class); assertEquals(0, result.getFailureCount()); } static public class NoExceptionTest { @Test(expected = Error.class) public void expectedException() { } } public void testExceptionNotThrown() throws Exception { JUnitCore core = new JUnitCore(); Result result = core.run(NoExceptionTest.class); assertEquals(1, result.getFailureCount()); assertEquals("Expected exception: java.lang.Error", result.getFailures().get(0).getMessage()); } static public class OneTimeSetup { @BeforeClass public static void once() { count++; } @Test public void one() { } @Test public void two() { } } public void testOneTimeSetup() throws Exception { count = 0; JUnitCore core = new JUnitCore(); core.run(OneTimeSetup.class); assertEquals(1, count); } static public class OneTimeTeardown { @AfterClass public static void once() { count++; } @Test public void one() { } @Test public void two() { } } public void testOneTimeTeardown() throws Exception { count = 0; JUnitCore core = new JUnitCore(); core.run(OneTimeTeardown.class); assertEquals(1, count); } static String log; public static class OrderTest { @BeforeClass public static void onceBefore() { log += "beforeClass "; } @Before public void before() { log += "before "; } @Test public void test() { log += "test "; } @After public void after() { log += "after "; } @AfterClass public static void onceAfter() { log += "afterClass "; } } public void testOrder() throws Exception { log = ""; JUnitCore core = new JUnitCore(); core.run(OrderTest.class); assertEquals("beforeClass before test after afterClass ", log); } static public class NonStaticOneTimeSetup { @BeforeClass public void once() { } @Test public void aTest() { } } public void testNonStaticOneTimeSetup() throws Exception { JUnitCore core = new JUnitCore(); Result result = core.run(NonStaticOneTimeSetup.class); assertEquals(1, result.getFailureCount()); } static public class ErrorInBeforeClass { @BeforeClass public static void before() throws Exception { throw new Exception(); } @Test public void test() { run = true; } } public void testErrorInBeforeClass() throws Exception { run = false; JUnitCore core = new JUnitCore(); Result result = core.run(ErrorInBeforeClass.class); assertFalse(run); assertEquals(1, result.getFailureCount()); Description description = result.getFailures().get(0).getDescription(); assertEquals(ErrorInBeforeClass.class.getName(), description.getDisplayName()); } static public class ErrorInAfterClass { @Test public void test() { run = true; } @AfterClass public static void after() throws Exception { throw new Exception(); } } public void testErrorInAfterClass() throws Exception { run = false; JUnitCore core = new JUnitCore(); Result result = core.run(ErrorInAfterClass.class); assertTrue(run); assertEquals(1, result.getFailureCount()); } static public class SuperInheritance { @BeforeClass static public void beforeClassSuper() { log += "Before class super "; } @AfterClass static public void afterClassSuper() { log += "After class super "; } @Before public void beforeSuper() { log += "Before super "; } @After public void afterSuper() { log += "After super "; } } static public class SubInheritance extends SuperInheritance { @BeforeClass static public void beforeClassSub() { log += "Before class sub "; } @AfterClass static public void afterClassSub() { log += "After class sub "; } @Before public void beforeSub() { log += "Before sub "; } @After public void afterSub() { log += "After sub "; } @Test public void test() { log += "Test "; } } public void testOrderingOfInheritance() throws Exception { log = ""; JUnitCore core = new JUnitCore(); core.run(SubInheritance.class); assertEquals("Before class super Before class sub Before super Before sub Test After sub After super After class sub After class super ", log); } static public class SuperShadowing { @Before public void before() { log += "Before super "; } @After public void after() { log += "After super "; } } static public class SubShadowing extends SuperShadowing { @Override @Before public void before() { log += "Before sub "; } @Override @After public void after() { log += "After sub "; } @Test public void test() { log += "Test "; } } public void testShadowing() throws Exception { log = ""; JUnitCore core = new JUnitCore(); core.run(SubShadowing.class); assertEquals("Before sub Test After sub ", log); } static public class SuperTest { @Test public void one() { log += "Super"; } @Test public void two() { log += "Two"; } } static public class SubTest extends SuperTest { @Override @Test public void one() { log += "Sub"; } } public void testTestInheritance() throws Exception { log = ""; JUnitCore core = new JUnitCore(); core.run(SubTest.class); // The order in which the test methods are called is unspecified assertTrue(log.contains("Sub")); assertTrue(log.contains("Two")); assertFalse(log.contains("Super")); } static public class RunAllAfters { @Before public void good() { } @Before public void bad() { throw new Error(); } @Test public void empty() { } @After public void one() { log += "one"; } @After public void two() { log += "two"; } } public void testRunAllAfters() { log = ""; JUnitCore core = new JUnitCore(); core.run(RunAllAfters.class); assertTrue(log.contains("one")); assertTrue(log.contains("two")); } static public class RunAllAftersRegardless { @Test public void empty() { } @After public void one() { log += "one"; throw new Error(); } @After public void two() { log += "two"; throw new Error(); } } public void testRunAllAftersRegardless() { log = ""; JUnitCore core = new JUnitCore(); Result result = core.run(RunAllAftersRegardless.class); assertTrue(log.contains("one")); assertTrue(log.contains("two")); assertEquals(2, result.getFailureCount()); } static public class RunAllAfterClasses { @Before public void good() { } @BeforeClass public static void bad() { throw new Error(); } @Test public void empty() { } @AfterClass public static void one() { log += "one"; } @AfterClass public static void two() { log += "two"; } } public void testRunAllAfterClasses() { log = ""; JUnitCore core = new JUnitCore(); core.run(RunAllAfterClasses.class); assertTrue(log.contains("one")); assertTrue(log.contains("two")); } static public class RunAllAfterClassesRegardless { @Test public void empty() { } @AfterClass static public void one() { log += "one"; throw new Error(); } @AfterClass static public void two() { log += "two"; throw new Error(); } } public void testRunAllAfterClassesRegardless() { log = ""; JUnitCore core = new JUnitCore(); Result result = core.run(RunAllAfterClassesRegardless.class); assertTrue(log.contains("one")); assertTrue(log.contains("two")); assertEquals(2, result.getFailureCount()); } } junit4-4.11/src/test/java/org/junit/tests/running/methods/ParameterizedTestMethodTest.java0000644000175000017500000000743112050524441031402 0ustar ebourgebourgpackage org.junit.tests.running.methods; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import junit.framework.JUnit4TestAdapter; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.junit.runners.model.InitializationError; @RunWith(Parameterized.class) public class ParameterizedTestMethodTest { @SuppressWarnings("all") public static class EverythingWrong { private EverythingWrong() { } @BeforeClass public void notStaticBC() { } @BeforeClass static void notPublicBC() { } @BeforeClass public static int nonVoidBC() { return 0; } @BeforeClass public static void argumentsBC(int i) { } @BeforeClass public static void fineBC() { } @AfterClass public void notStaticAC() { } @AfterClass static void notPublicAC() { } @AfterClass public static int nonVoidAC() { return 0; } @AfterClass public static void argumentsAC(int i) { } @AfterClass public static void fineAC() { } @After public static void staticA() { } @After void notPublicA() { } @After public int nonVoidA() { return 0; } @After public void argumentsA(int i) { } @After public void fineA() { } @Before public static void staticB() { } @Before void notPublicB() { } @Before public int nonVoidB() { return 0; } @Before public void argumentsB(int i) { } @Before public void fineB() { } @Test public static void staticT() { } @Test void notPublicT() { } @Test public int nonVoidT() { return 0; } @Test public void argumentsT(int i) { } @Test public void fineT() { } } private Class fClass; private int fErrorCount; static public class SuperWrong { @Test void notPublic() { } } static public class SubWrong extends SuperWrong { @Test public void justFine() { } } static public class SubShadows extends SuperWrong { @Override @Test public void notPublic() { } } public ParameterizedTestMethodTest(Class class1, int errorCount) { fClass = class1; fErrorCount = errorCount; } @Parameters public static Collection params() { return Arrays.asList(new Object[][]{ {EverythingWrong.class, 1 + 4 * 5}, {SubWrong.class, 1}, {SubShadows.class, 0}}); } private List validateAllMethods(Class clazz) { try { new BlockJUnit4ClassRunner(clazz); } catch (InitializationError e) { return e.getCauses(); } return Collections.emptyList(); } @Test public void testFailures() throws Exception { List problems = validateAllMethods(fClass); assertEquals(fErrorCount, problems.size()); } public static junit.framework.Test suite() { return new JUnit4TestAdapter(ParameterizedTestMethodTest.class); } } junit4-4.11/src/test/java/org/junit/tests/running/methods/TimeoutTest.java0000644000175000017500000001410212050524441026224 0ustar ebourgebourgpackage org.junit.tests.running.methods; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import junit.framework.JUnit4TestAdapter; import junit.framework.TestResult; import org.junit.After; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.JUnitCore; import org.junit.runner.Result; public class TimeoutTest { static public class FailureWithTimeoutTest { @Test(timeout = 1000) public void failure() { fail(); } } @Test public void failureWithTimeout() throws Exception { JUnitCore core = new JUnitCore(); Result result = core.run(FailureWithTimeoutTest.class); assertEquals(1, result.getRunCount()); assertEquals(1, result.getFailureCount()); assertEquals(AssertionError.class, result.getFailures().get(0).getException().getClass()); } static public class FailureWithTimeoutRunTimeExceptionTest { @Test(timeout = 1000) public void failure() { throw new NullPointerException(); } } @Test public void failureWithTimeoutRunTimeException() throws Exception { JUnitCore core = new JUnitCore(); Result result = core.run(FailureWithTimeoutRunTimeExceptionTest.class); assertEquals(1, result.getRunCount()); assertEquals(1, result.getFailureCount()); assertEquals(NullPointerException.class, result.getFailures().get(0).getException().getClass()); } static public class SuccessWithTimeoutTest { @Test(timeout = 1000) public void success() { } } @Test public void successWithTimeout() throws Exception { JUnitCore core = new JUnitCore(); Result result = core.run(SuccessWithTimeoutTest.class); assertEquals(1, result.getRunCount()); assertEquals(0, result.getFailureCount()); } static public class TimeoutFailureTest { @Test(timeout = 100) public void success() throws InterruptedException { Thread.sleep(40000); } } @Ignore("was breaking gump") @Test public void timeoutFailure() throws Exception { JUnitCore core = new JUnitCore(); Result result = core.run(TimeoutFailureTest.class); assertEquals(1, result.getRunCount()); assertEquals(1, result.getFailureCount()); assertEquals(InterruptedException.class, result.getFailures().get(0).getException().getClass()); } static public class InfiniteLoopTest { @Test(timeout = 100) public void failure() { infiniteLoop(); } private void infiniteLoop() { for (; ; ) { try { Thread.sleep(10); } catch (InterruptedException e) { } } } } @Test public void infiniteLoop() throws Exception { JUnitCore core = new JUnitCore(); Result result = core.run(InfiniteLoopTest.class); assertEquals(1, result.getRunCount()); assertEquals(1, result.getFailureCount()); Throwable exception = result.getFailures().get(0).getException(); assertTrue(exception.getMessage().contains("test timed out after 100 milliseconds")); } static public class ImpatientLoopTest { @Test(timeout = 1) public void failure() { infiniteLoop(); } private void infiniteLoop() { for (; ; ) ; } } @Ignore("This breaks sporadically with time differences just slightly more than 200ms") @Test public void infiniteLoopRunsForApproximatelyLengthOfTimeout() throws Exception { // "prime the pump": running these beforehand makes the runtimes more predictable // (because of class loading?) JUnitCore.runClasses(InfiniteLoopTest.class, ImpatientLoopTest.class); long longTime = runAndTime(InfiniteLoopTest.class); long shortTime = runAndTime(ImpatientLoopTest.class); long difference = longTime - shortTime; assertTrue(String.format("Difference was %sms", difference), difference < 200); } private long runAndTime(Class clazz) { JUnitCore core = new JUnitCore(); long startTime = System.currentTimeMillis(); core.run(clazz); long totalTime = System.currentTimeMillis() - startTime; return totalTime; } @Test public void stalledThreadAppearsInStackTrace() throws Exception { JUnitCore core = new JUnitCore(); Result result = core.run(InfiniteLoopTest.class); assertEquals(1, result.getRunCount()); assertEquals(1, result.getFailureCount()); Throwable exception = result.getFailures().get(0).getException(); Writer buffer = new StringWriter(); PrintWriter writer = new PrintWriter(buffer); exception.printStackTrace(writer); assertThat(buffer.toString(), containsString("infiniteLoop")); // Make sure we have the stalled frame on the stack somewhere } @Test public void compatibility() { TestResult result = new TestResult(); new JUnit4TestAdapter(InfiniteLoopTest.class).run(result); assertEquals(1, result.errorCount()); } public static class WillTimeOut { static boolean afterWasCalled = false; @Test(timeout = 1) public void test() { for (; ; ) { try { Thread.sleep(10000); } catch (InterruptedException e) { // ok, tests are over } } } @After public void after() { afterWasCalled = true; } } @Test public void makeSureAfterIsCalledAfterATimeout() { JUnitCore.runClasses(WillTimeOut.class); assertThat(WillTimeOut.afterWasCalled, is(true)); } } junit4-4.11/src/test/java/org/junit/tests/running/methods/ExpectedTest.java0000644000175000017500000000401612050524441026342 0ustar ebourgebourgpackage org.junit.tests.running.methods; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class ExpectedTest { public static class Expected { @Test(expected = Exception.class) public void expected() throws Exception { throw new Exception(); } } @Test public void expected() { JUnitCore core = new JUnitCore(); Result result = core.run(Expected.class); assertTrue(result.wasSuccessful()); } public static class Unexpected { @Test(expected = Exception.class) public void expected() throws Exception { throw new Error(); } } @Test public void unexpected() { Result result = JUnitCore.runClasses(Unexpected.class); Failure failure = result.getFailures().get(0); String message = failure.getMessage(); assertTrue(message.contains("expected but was")); assertEquals(Error.class, failure.getException().getCause().getClass()); } public static class NoneThrown { @Test(expected = Exception.class) public void nothing() { } } @Test public void noneThrown() { JUnitCore core = new JUnitCore(); Result result = core.run(NoneThrown.class); assertFalse(result.wasSuccessful()); String message = result.getFailures().get(0).getMessage(); assertTrue(message.contains("Expected exception: java.lang.Exception")); } public static class ExpectSuperclass { @Test(expected = RuntimeException.class) public void throwsSubclass() { throw new ClassCastException(); } } @Test public void expectsSuperclass() { assertTrue(new JUnitCore().run(ExpectSuperclass.class).wasSuccessful()); } } junit4-4.11/src/test/java/org/junit/tests/running/classes/0000755000175000017500000000000012050524441023067 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/running/classes/EnclosedTest.java0000644000175000017500000000266712050524441026341 0ustar ebourgebourgpackage org.junit.tests.running.classes; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.JUnitCore; import org.junit.runner.Request; import org.junit.runner.Result; import org.junit.runner.RunWith; import org.junit.runner.Runner; public class EnclosedTest { @RunWith(Enclosed.class) public static class Enclosing { public static class A { @Test public void a() { } @Test public void b() { } } public static class B { @Test public void a() { } @Test public void b() { } @Test public void c() { } } } @Test public void enclosedRunnerPlansEnclosedClasses() throws Exception { Runner runner = Request.aClass(Enclosing.class).getRunner(); assertEquals(5, runner.testCount()); } @Test public void enclosedRunnerRunsEnclosedClasses() throws Exception { Result result = JUnitCore.runClasses(Enclosing.class); assertEquals(5, result.getRunCount()); } @Test public void enclosedRunnerIsNamedForEnclosingClass() throws Exception { assertEquals(Enclosing.class.getName(), Request.aClass(Enclosing.class) .getRunner().getDescription().getDisplayName()); } } junit4-4.11/src/test/java/org/junit/tests/running/classes/IgnoreClassTest.java0000644000175000017500000000131012050524441026776 0ustar ebourgebourgpackage org.junit.tests.running.classes; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.JUnitCore; import org.junit.runner.Result; public class IgnoreClassTest { @Ignore("For a good reason") public static class IgnoreMe { @Test public void iFail() { fail(); } @Test public void iFailToo() { fail(); } } @Test public void ignoreClass() { Result result = JUnitCore.runClasses(IgnoreMe.class); assertEquals(0, result.getFailureCount()); assertEquals(1, result.getIgnoreCount()); } } junit4-4.11/src/test/java/org/junit/tests/running/classes/TestClassTest.java0000644000175000017500000000503712050524441026504 0ustar ebourgebourgpackage org.junit.tests.running.classes; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; import org.junit.runners.model.TestClass; public class TestClassTest { public static class TwoConstructors { public TwoConstructors() { } public TwoConstructors(int x) { } } @Test(expected = IllegalArgumentException.class) public void complainIfMultipleConstructors() { new TestClass(TwoConstructors.class); } public static class ManyMethods { @Test public void a() { } @Before public void b() { } @Ignore @Test public void c() { } @Ignore @After public void d() { } public void e() { } @BeforeClass public void f() { } public void g() { } @AfterClass public void h() { } @Test public void i() { } @Test public void j() { } } public static class SuperclassWithField { @Rule public TestRule x; } public static class SubclassWithField extends SuperclassWithField { @Rule public TestRule x; } @Test public void fieldsOnSubclassesShadowSuperclasses() { assertThat(new TestClass(SubclassWithField.class).getAnnotatedFields( Rule.class).size(), is(1)); } public static class OuterClass { public class NonStaticInnerClass { } } @Test public void identifyNonStaticInnerClass() { assertThat( new TestClass(OuterClass.NonStaticInnerClass.class) .isANonStaticInnerClass(), is(true)); } public static class OuterClass2 { public static class StaticInnerClass { } } @Test public void dontMarkStaticInnerClassAsNonStatic() { assertThat( new TestClass(OuterClass2.StaticInnerClass.class) .isANonStaticInnerClass(), is(false)); } public static class SimpleClass { } @Test public void dontMarkNonInnerClassAsInnerClass() { assertThat(new TestClass(SimpleClass.class).isANonStaticInnerClass(), is(false)); } } junit4-4.11/src/test/java/org/junit/tests/running/classes/RunWithTest.java0000644000175000017500000000416212050524441026175 0ustar ebourgebourgpackage org.junit.tests.running.classes; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.RunWith; import org.junit.runner.Runner; import org.junit.runner.notification.RunNotifier; public class RunWithTest { private static String log; public static class ExampleRunner extends Runner { public ExampleRunner(Class klass) { log += "initialize"; } @Override public void run(RunNotifier notifier) { log += "run"; } @Override public int testCount() { log += "count"; return 0; } @Override public Description getDescription() { log += "plan"; return Description.createSuiteDescription("example"); } } @RunWith(ExampleRunner.class) public static class ExampleTest { } @Test public void run() { log = ""; JUnitCore.runClasses(ExampleTest.class); assertTrue(log.contains("plan")); assertTrue(log.contains("initialize")); assertTrue(log.contains("run")); } public static class SubExampleTest extends ExampleTest { } @Test public void runWithExtendsToSubclasses() { log = ""; JUnitCore.runClasses(SubExampleTest.class); assertTrue(log.contains("run")); } public static class BadRunner extends Runner { @Override public Description getDescription() { return null; } @Override public void run(RunNotifier notifier) { // do nothing } } @RunWith(BadRunner.class) public static class Empty { } @Test public void characterizeErrorMessageFromBadRunner() { assertEquals( "Custom runner class BadRunner should have a public constructor with signature BadRunner(Class testClass)", JUnitCore.runClasses(Empty.class).getFailures().get(0) .getMessage()); } } junit4-4.11/src/test/java/org/junit/tests/running/classes/ParentRunnerFilteringTest.java0000644000175000017500000001355212050524441031067 0ustar ebourgebourgpackage org.junit.tests.running.classes; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.junit.experimental.results.PrintableResult.testResult; import static org.junit.experimental.results.ResultMatchers.hasSingleFailureContaining; import static org.junit.runner.Description.createSuiteDescription; import static org.junit.runner.Description.createTestDescription; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.Request; import org.junit.runner.Result; import org.junit.runner.RunWith; import org.junit.runner.Runner; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import org.junit.runners.model.InitializationError; import org.junit.runners.model.RunnerBuilder; public class ParentRunnerFilteringTest { private static Filter notThisMethodName(final String methodName) { return new Filter() { @Override public boolean shouldRun(Description description) { return description.getMethodName() == null || !description.getMethodName().equals(methodName); } @Override public String describe() { return "don't run method name: " + methodName; } }; } private static class CountingFilter extends Filter { private final Map countMap = new HashMap(); @Override public boolean shouldRun(Description description) { Integer count = countMap.get(description); if (count == null) { countMap.put(description, 1); } else { countMap.put(description, count + 1); } return true; } @Override public String describe() { return "filter counter"; } public int getCount(final Description desc) { if (!countMap.containsKey(desc)) { throw new IllegalArgumentException("Looking for " + desc + ", but only contains: " + countMap.keySet()); } return countMap.get(desc); } } public static class ExampleTest { @Test public void test1() throws Exception { // passes } } @RunWith(Suite.class) @SuiteClasses({ExampleTest.class}) public static class ExampleSuite { } @Test public void testSuiteFiltering() throws Exception { Runner runner = Request.aClass(ExampleSuite.class).getRunner(); Filter filter = notThisMethodName("test1"); try { filter.apply(runner); } catch (NoTestsRemainException e) { return; } fail("Expected 'NoTestsRemainException' due to complete filtering"); } public static class SuiteWithUnmodifyableChildList extends Suite { public SuiteWithUnmodifyableChildList( Class klass, RunnerBuilder builder) throws InitializationError { super(klass, builder); } @Override protected List getChildren() { return Collections.unmodifiableList(super.getChildren()); } } @RunWith(SuiteWithUnmodifyableChildList.class) @SuiteClasses({ExampleTest.class}) public static class ExampleSuiteWithUnmodifyableChildList { } @Test public void testSuiteFilteringWithUnmodifyableChildList() throws Exception { Runner runner = Request.aClass(ExampleSuiteWithUnmodifyableChildList.class) .getRunner(); Filter filter = notThisMethodName("test1"); try { filter.apply(runner); } catch (NoTestsRemainException e) { return; } fail("Expected 'NoTestsRemainException' due to complete filtering"); } @Test public void testRunSuiteFiltering() throws Exception { Request request = Request.aClass(ExampleSuite.class); Request requestFiltered = request.filterWith(notThisMethodName("test1")); assertThat(testResult(requestFiltered), hasSingleFailureContaining("don't run method name: test1")); } @Test public void testCountClassFiltering() throws Exception { JUnitCore junitCore = new JUnitCore(); Request request = Request.aClass(ExampleTest.class); CountingFilter countingFilter = new CountingFilter(); Request requestFiltered = request.filterWith(countingFilter); Result result = junitCore.run(requestFiltered); assertEquals(1, result.getRunCount()); assertEquals(0, result.getFailureCount()); Description desc = createTestDescription(ExampleTest.class, "test1"); assertEquals(1, countingFilter.getCount(desc)); } @Test public void testCountSuiteFiltering() throws Exception { Class suiteClazz = ExampleSuite.class; Class clazz = ExampleTest.class; JUnitCore junitCore = new JUnitCore(); Request request = Request.aClass(suiteClazz); CountingFilter countingFilter = new CountingFilter(); Request requestFiltered = request.filterWith(countingFilter); Result result = junitCore.run(requestFiltered); assertEquals(1, result.getRunCount()); assertEquals(0, result.getFailureCount()); Description suiteDesc = createSuiteDescription(clazz); assertEquals(1, countingFilter.getCount(suiteDesc)); Description desc = createTestDescription(ExampleTest.class, "test1"); assertEquals(1, countingFilter.getCount(desc)); } }junit4-4.11/src/test/java/org/junit/tests/running/classes/ParameterizedTestTest.java0000644000175000017500000002535612050524441030241 0ustar ebourgebourgpackage org.junit.tests.running.classes; import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.experimental.results.PrintableResult.testResult; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.Request; import org.junit.runner.Result; import org.junit.runner.RunWith; import org.junit.runner.Runner; import org.junit.runner.notification.Failure; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import org.junit.runners.model.InitializationError; public class ParameterizedTestTest { @RunWith(Parameterized.class) static public class FibonacciTest { @Parameters(name = "{index}: fib({0})={1}") public static Iterable data() { return Arrays.asList(new Object[][]{{0, 0}, {1, 1}, {2, 1}, {3, 2}, {4, 3}, {5, 5}, {6, 8}}); } private final int fInput; private final int fExpected; public FibonacciTest(int input, int expected) { fInput = input; fExpected = expected; } @Test public void test() { assertEquals(fExpected, fib(fInput)); } private int fib(int x) { return 0; } } @Test public void count() { Result result = JUnitCore.runClasses(FibonacciTest.class); assertEquals(7, result.getRunCount()); assertEquals(6, result.getFailureCount()); } @Test public void failuresNamedCorrectly() { Result result = JUnitCore.runClasses(FibonacciTest.class); assertEquals( "test[1: fib(1)=1](" + FibonacciTest.class.getName() + ")", result.getFailures().get(0).getTestHeader()); } @Test public void countBeforeRun() throws Exception { Runner runner = Request.aClass(FibonacciTest.class).getRunner(); assertEquals(7, runner.testCount()); } @Test public void plansNamedCorrectly() throws Exception { Runner runner = Request.aClass(FibonacciTest.class).getRunner(); Description description = runner.getDescription(); assertEquals("[0: fib(0)=0]", description.getChildren().get(0) .getDisplayName()); } @RunWith(Parameterized.class) public static class ParameterizedWithoutSpecialTestname { @Parameters public static Collection data() { return Arrays.asList(new Object[][]{{3}, {3}}); } public ParameterizedWithoutSpecialTestname(Object something) { } @Test public void testSomething() { } } @Test public void usesIndexAsTestName() { Runner runner = Request .aClass(ParameterizedWithoutSpecialTestname.class).getRunner(); Description description = runner.getDescription(); assertEquals("[1]", description.getChildren().get(1).getDisplayName()); } @RunWith(Parameterized.class) static public class FibonacciWithParameterizedFieldTest { @Parameters public static Collection data() { return Arrays.asList(new Object[][]{{0, 0}, {1, 1}, {2, 1}, {3, 2}, {4, 3}, {5, 5}, {6, 8}}); } @Parameter(0) public int fInput; @Parameter(1) public int fExpected; @Test public void test() { assertEquals(fExpected, fib(fInput)); } private int fib(int x) { return 0; } } @Test public void countWithParameterizedField() { Result result = JUnitCore.runClasses(FibonacciWithParameterizedFieldTest.class); assertEquals(7, result.getRunCount()); assertEquals(6, result.getFailureCount()); } @Test public void failuresNamedCorrectlyWithParameterizedField() { Result result = JUnitCore.runClasses(FibonacciWithParameterizedFieldTest.class); assertEquals(String .format("test[1](%s)", FibonacciWithParameterizedFieldTest.class.getName()), result .getFailures().get(0).getTestHeader()); } @Test public void countBeforeRunWithParameterizedField() throws Exception { Runner runner = Request.aClass(FibonacciWithParameterizedFieldTest.class).getRunner(); assertEquals(7, runner.testCount()); } @Test public void plansNamedCorrectlyWithParameterizedField() throws Exception { Runner runner = Request.aClass(FibonacciWithParameterizedFieldTest.class).getRunner(); Description description = runner.getDescription(); assertEquals("[0]", description.getChildren().get(0).getDisplayName()); } @RunWith(Parameterized.class) static public class BadIndexForAnnotatedFieldTest { @Parameters public static Collection data() { return Arrays.asList(new Object[][]{{0}}); } @Parameter(2) public int fInput; public int fExpected; @Test public void test() { assertEquals(fExpected, fib(fInput)); } private int fib(int x) { return 0; } } @Test public void failureOnInitialization() { Result result = JUnitCore.runClasses(BadIndexForAnnotatedFieldTest.class); assertEquals(2, result.getFailureCount()); List failures = result.getFailures(); assertEquals("Invalid @Parameter value: 2. @Parameter fields counted: 1. Please use an index between 0 and 0.", failures.get(0).getException().getMessage()); assertEquals("@Parameter(0) is never used.", failures.get(1).getException().getMessage()); } @RunWith(Parameterized.class) static public class BadNumberOfAnnotatedFieldTest { @Parameters public static Collection data() { return Arrays.asList(new Object[][]{{0, 0}}); } @Parameter(0) public int fInput; public int fExpected; @Test public void test() { assertEquals(fExpected, fib(fInput)); } private int fib(int x) { return 0; } } @Test public void numberOfFieldsAndParametersShouldMatch() { Result result = JUnitCore.runClasses(BadNumberOfAnnotatedFieldTest.class); assertEquals(1, result.getFailureCount()); List failures = result.getFailures(); assertTrue(failures.get(0).getException().getMessage().contains("Wrong number of parameters and @Parameter fields. @Parameter fields counted: 1, available parameters: 2.")); } private static String fLog; @RunWith(Parameterized.class) static public class BeforeAndAfter { @BeforeClass public static void before() { fLog += "before "; } @AfterClass public static void after() { fLog += "after "; } public BeforeAndAfter(int x) { } @Parameters public static Collection data() { return Arrays.asList(new Object[][]{{3}}); } @Test public void aTest() { } } @Test public void beforeAndAfterClassAreRun() { fLog = ""; JUnitCore.runClasses(BeforeAndAfter.class); assertEquals("before after ", fLog); } @RunWith(Parameterized.class) static public class EmptyTest { @BeforeClass public static void before() { fLog += "before "; } @AfterClass public static void after() { fLog += "after "; } } @Test public void validateClassCatchesNoParameters() { Result result = JUnitCore.runClasses(EmptyTest.class); assertEquals(1, result.getFailureCount()); } @RunWith(Parameterized.class) static public class IncorrectTest { @Test public int test() { return 0; } @Parameters public static Collection data() { return Collections.singletonList(new Object[]{1}); } } @Test public void failuresAddedForBadTestMethod() throws Exception { Result result = JUnitCore.runClasses(IncorrectTest.class); assertEquals(1, result.getFailureCount()); } @RunWith(Parameterized.class) static public class ProtectedParametersTest { @Parameters protected static Collection data() { return Collections.emptyList(); } @Test public void aTest() { } } @Test public void meaningfulFailureWhenParametersNotPublic() throws Exception { Result result = JUnitCore.runClasses(ProtectedParametersTest.class); String expected = String.format( "No public static parameters method on class %s", ProtectedParametersTest.class.getName()); assertEquals(expected, result.getFailures().get(0).getMessage()); } @RunWith(Parameterized.class) static public class WrongElementType { @Parameters public static Iterable data() { return Arrays.asList("a", "b", "c"); } @Test public void aTest() { } } @Test public void meaningfulFailureWhenParametersAreNotArrays() { assertThat( testResult(WrongElementType.class).toString(), containsString("WrongElementType.data() must return an Iterable of arrays.")); } @RunWith(Parameterized.class) static public class ParametersNotIterable { @Parameters public static String data() { return "foo"; } @Test public void aTest() { } } @Test public void meaningfulFailureWhenParametersAreNotAnIterable() { assertThat( testResult(ParametersNotIterable.class).toString(), containsString("ParametersNotIterable.data() must return an Iterable of arrays.")); } @RunWith(Parameterized.class) static public class PrivateConstructor { private PrivateConstructor(int x) { } @Parameters public static Collection data() { return Arrays.asList(new Object[][]{{3}}); } @Test public void aTest() { } } @Test(expected = InitializationError.class) public void exceptionWhenPrivateConstructor() throws Throwable { new Parameterized(PrivateConstructor.class); } }junit4-4.11/src/test/java/org/junit/tests/running/classes/SuiteTest.java0000644000175000017500000001263312050524441025670 0ustar ebourgebourgpackage org.junit.tests.running.classes; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.experimental.results.PrintableResult.testResult; import static org.junit.experimental.results.ResultMatchers.hasSingleFailureContaining; import java.util.List; import junit.framework.JUnit4TestAdapter; import junit.framework.TestResult; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.JUnitCore; import org.junit.runner.Request; import org.junit.runner.Result; import org.junit.runner.RunWith; import org.junit.runner.Runner; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; public class SuiteTest { public static class TestA { @Test public void pass() { } } public static class TestB { @Test public void fail() { Assert.fail(); } } @RunWith(Suite.class) @SuiteClasses({TestA.class, TestB.class}) public static class All { } public static class InheritsAll extends All { } @Test public void ensureTestIsRun() { JUnitCore core = new JUnitCore(); Result result = core.run(All.class); assertEquals(2, result.getRunCount()); assertEquals(1, result.getFailureCount()); } @Test public void ensureInheritedTestIsRun() { JUnitCore core = new JUnitCore(); Result result = core.run(InheritsAll.class); assertEquals(2, result.getRunCount()); assertEquals(1, result.getFailureCount()); } @Test public void suiteTestCountIsCorrect() throws Exception { Runner runner = Request.aClass(All.class).getRunner(); assertEquals(2, runner.testCount()); } @Test public void ensureSuitesWorkWithForwardCompatibility() { junit.framework.Test test = new JUnit4TestAdapter(All.class); TestResult result = new TestResult(); test.run(result); assertEquals(2, result.runCount()); } @Test public void forwardCompatibilityWorksWithGetTests() { JUnit4TestAdapter adapter = new JUnit4TestAdapter(All.class); List tests = adapter.getTests(); assertEquals(2, tests.size()); } @Test public void forwardCompatibilityWorksWithTestCount() { JUnit4TestAdapter adapter = new JUnit4TestAdapter(All.class); assertEquals(2, adapter.countTestCases()); } private static String log = ""; @RunWith(Suite.class) @SuiteClasses({TestA.class, TestB.class}) public static class AllWithBeforeAndAfterClass { @BeforeClass public static void before() { log += "before "; } @AfterClass public static void after() { log += "after "; } } @Test public void beforeAndAfterClassRunOnSuite() { log = ""; JUnitCore.runClasses(AllWithBeforeAndAfterClass.class); assertEquals("before after ", log); } @RunWith(Suite.class) public static class AllWithOutAnnotation { } @Test public void withoutSuiteClassAnnotationProducesFailure() { Result result = JUnitCore.runClasses(AllWithOutAnnotation.class); assertEquals(1, result.getFailureCount()); String expected = String.format( "class '%s' must have a SuiteClasses annotation", AllWithOutAnnotation.class.getName()); assertEquals(expected, result.getFailures().get(0).getMessage()); } @RunWith(Suite.class) @SuiteClasses(InfiniteLoop.class) static public class InfiniteLoop { } @Test public void whatHappensWhenASuiteHasACycle() { Result result = JUnitCore.runClasses(InfiniteLoop.class); assertEquals(1, result.getFailureCount()); } @RunWith(Suite.class) @SuiteClasses({BiInfiniteLoop.class, BiInfiniteLoop.class}) static public class BiInfiniteLoop { } @Test public void whatHappensWhenASuiteHasAForkingCycle() { Result result = JUnitCore.runClasses(BiInfiniteLoop.class); assertEquals(2, result.getFailureCount()); } // The interesting case here is that Hydra indirectly contains two copies of // itself (if it only contains one, Java's StackOverflowError eventually // bails us out) @RunWith(Suite.class) @SuiteClasses({Hercules.class}) static public class Hydra { } @RunWith(Suite.class) @SuiteClasses({Hydra.class, Hydra.class}) static public class Hercules { } @Test public void whatHappensWhenASuiteContainsItselfIndirectly() { Result result = JUnitCore.runClasses(Hydra.class); assertEquals(2, result.getFailureCount()); } @RunWith(Suite.class) @SuiteClasses({}) public class WithoutDefaultConstructor { public WithoutDefaultConstructor(int i) { } } @Test public void suiteShouldBeOKwithNonDefaultConstructor() throws Exception { Result result = JUnitCore.runClasses(WithoutDefaultConstructor.class); assertTrue(result.wasSuccessful()); } @RunWith(Suite.class) public class NoSuiteClassesAnnotation { } @Test public void suiteShouldComplainAboutNoSuiteClassesAnnotation() { assertThat(testResult(NoSuiteClassesAnnotation.class), hasSingleFailureContaining("SuiteClasses")); } } junit4-4.11/src/test/java/org/junit/tests/running/classes/BlockJUnit4ClassRunnerTest.java0000644000175000017500000000177112050524441031050 0ustar ebourgebourgpackage org.junit.tests.running.classes; import static org.junit.Assert.assertEquals; import java.util.List; import org.junit.Test; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.InitializationError; public class BlockJUnit4ClassRunnerTest { public static class OuterClass { public class Enclosed { @Test public void test() { } } } @Test public void detectNonStaticEnclosedClass() throws Exception { try { new BlockJUnit4ClassRunner(OuterClass.Enclosed.class); } catch (InitializationError e) { List causes = e.getCauses(); assertEquals("Wrong number of causes.", 1, causes.size()); assertEquals( "Wrong exception.", "The inner class org.junit.tests.running.classes.BlockJUnit4ClassRunnerTest$OuterClass$Enclosed is not static.", causes.get(0).getMessage()); } } }junit4-4.11/src/test/java/org/junit/tests/running/classes/ParentRunnerTest.java0000644000175000017500000001045612050524441027223 0ustar ebourgebourgpackage org.junit.tests.running.classes; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import java.util.List; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.Request; import org.junit.runner.Result; import org.junit.runner.manipulation.Filter; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.ParentRunner; import org.junit.runners.model.InitializationError; import org.junit.runners.model.RunnerScheduler; import org.junit.tests.experimental.rules.RuleFieldValidatorTest.TestWithNonStaticClassRule; import org.junit.tests.experimental.rules.RuleFieldValidatorTest.TestWithProtectedClassRule; public class ParentRunnerTest { public static String log = ""; public static class FruitTest { @Test public void apple() { log += "apple "; } @Test public void /* must hash-sort after "apple" */Banana() { log += "banana "; } } @Test public void useChildHarvester() throws InitializationError { log = ""; ParentRunner runner = new BlockJUnit4ClassRunner(FruitTest.class); runner.setScheduler(new RunnerScheduler() { public void schedule(Runnable childStatement) { log += "before "; childStatement.run(); log += "after "; } public void finished() { log += "afterAll "; } }); runner.run(new RunNotifier()); assertEquals("before apple after before banana after afterAll ", log); } @Test public void testMultipleFilters() throws Exception { JUnitCore junitCore = new JUnitCore(); Request request = Request.aClass(ExampleTest.class); Request requestFiltered = request.filterWith(new Exclude("test1")); Request requestFilteredFiltered = requestFiltered .filterWith(new Exclude("test2")); Result result = junitCore.run(requestFilteredFiltered); assertThat(result.getFailures(), isEmpty()); assertEquals(1, result.getRunCount()); } private Matcher> isEmpty() { return new TypeSafeMatcher>() { public void describeTo(org.hamcrest.Description description) { description.appendText("is empty"); } @Override public boolean matchesSafely(List item) { return item.size() == 0; } }; } private static class Exclude extends Filter { private String methodName; public Exclude(String methodName) { this.methodName = methodName; } @Override public boolean shouldRun(Description description) { return !description.getMethodName().equals(methodName); } @Override public String describe() { return "filter method name: " + methodName; } } public static class ExampleTest { @Test public void test1() throws Exception { } @Test public void test2() throws Exception { } @Test public void test3() throws Exception { } } @Test public void failWithHelpfulMessageForProtectedClassRule() { assertClassHasFailureMessage(TestWithProtectedClassRule.class, "The @ClassRule 'temporaryFolder' must be public."); } @Test public void failWithHelpfulMessageForNonStaticClassRule() { assertClassHasFailureMessage(TestWithNonStaticClassRule.class, "The @ClassRule 'temporaryFolder' must be static."); } private void assertClassHasFailureMessage(Class klass, String message) { JUnitCore junitCore = new JUnitCore(); Request request = Request.aClass(klass); Result result = junitCore.run(request); assertThat(result.getFailureCount(), is(2)); //the second failure is no runnable methods assertThat(result.getFailures().get(0).getMessage(), is(equalTo(message))); } } junit4-4.11/src/test/java/org/junit/tests/running/classes/UseSuiteAsASuperclassTest.java0000644000175000017500000000212512050524441030772 0ustar ebourgebourgpackage org.junit.tests.running.classes; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.junit.Test; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.model.InitializationError; public class UseSuiteAsASuperclassTest { public static class TestA { @Test public void pass() { } } public static class TestB { @Test public void dontPass() { fail(); } } public static class MySuite extends Suite { public MySuite(Class klass) throws InitializationError { super(klass, new Class[]{TestA.class, TestB.class}); } } @RunWith(MySuite.class) public static class AllWithMySuite { } @Test public void ensureTestsAreRun() { JUnitCore core = new JUnitCore(); Result result = core.run(AllWithMySuite.class); assertEquals(2, result.getRunCount()); assertEquals(1, result.getFailureCount()); } } junit4-4.11/src/test/java/org/junit/tests/running/core/0000755000175000017500000000000012050524441022362 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/running/core/CommandLineTest.java0000644000175000017500000000337012050524441026256 0ustar ebourgebourgpackage org.junit.tests.running.core; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.JUnitCore; public class CommandLineTest { private ByteArrayOutputStream results; private PrintStream oldOut; private static boolean testWasRun; @Before public void before() { oldOut = System.out; results = new ByteArrayOutputStream(); System.setOut(new PrintStream(results)); } @After public void after() { System.setOut(oldOut); } static public class Example { @Test public void test() { testWasRun = true; } } @Test public void runATest() { testWasRun = false; new MainRunner().runWithCheckForSystemExit(new Runnable() { public void run() { JUnitCore.main("org.junit.tests.running.core.CommandLineTest$Example"); } }); assertTrue(testWasRun); } @Test public void runAClass() { testWasRun = false; JUnitCore.runClasses(Example.class); assertTrue(testWasRun); } private static int fCount; static public class Count { @Test public void increment() { fCount++; } } @Test public void runTwoClassesAsArray() { fCount = 0; JUnitCore.runClasses(new Class[]{Count.class, Count.class}); assertEquals(2, fCount); } @Test public void runTwoClasses() { fCount = 0; JUnitCore.runClasses(Count.class, Count.class); assertEquals(2, fCount); } } junit4-4.11/src/test/java/org/junit/tests/running/core/MainRunner.java0000644000175000017500000002174112050524441025310 0ustar ebourgebourgpackage org.junit.tests.running.core; import java.io.ByteArrayOutputStream; import java.io.FileDescriptor; import java.io.PrintStream; import java.net.InetAddress; import java.security.Permission; public class MainRunner { private static class ExitException extends SecurityException { private static final long serialVersionUID = -9104651568237766642L; private final int status; public ExitException(int status) { super(""); this.status = status; } public int getStatus() { return status; } } /** * A {@code NoExitSecurityManager} throws a {@link ExitException} exception * whenever {@link #checkExit(int)} is called. All other method calls are * delegated to the original security manager. */ public class NoExitSecurityManager extends SecurityManager { private final SecurityManager originalSecurityManager; public NoExitSecurityManager(SecurityManager originalSecurityManager) { this.originalSecurityManager = originalSecurityManager; } @Override public void checkExit(int status) { throw new ExitException(status); } @Override public boolean getInCheck() { return (originalSecurityManager != null) && originalSecurityManager.getInCheck(); } @Override public Object getSecurityContext() { return (originalSecurityManager == null) ? super.getSecurityContext() : originalSecurityManager.getSecurityContext(); } @Override public void checkPermission(Permission perm) { if (originalSecurityManager != null) { originalSecurityManager.checkPermission(perm); } } @Override public void checkPermission(Permission perm, Object context) { if (originalSecurityManager != null) { originalSecurityManager.checkPermission(perm, context); } } @Override public void checkCreateClassLoader() { if (originalSecurityManager != null) { originalSecurityManager.checkCreateClassLoader(); } } @Override public void checkAccess(Thread t) { if (originalSecurityManager != null) { originalSecurityManager.checkAccess(t); } } @Override public void checkAccess(ThreadGroup g) { if (originalSecurityManager != null) { originalSecurityManager.checkAccess(g); } } @Override public void checkExec(String cmd) { if (originalSecurityManager != null) { originalSecurityManager.checkExec(cmd); } } @Override public void checkLink(String lib) { if (originalSecurityManager != null) { originalSecurityManager.checkLink(lib); } } @Override public void checkRead(FileDescriptor fd) { if (originalSecurityManager != null) { originalSecurityManager.checkRead(fd); } } @Override public void checkRead(String file) { if (originalSecurityManager != null) { originalSecurityManager.checkRead(file); } } @Override public void checkRead(String file, Object context) { if (originalSecurityManager != null) { originalSecurityManager.checkRead(file, context); } } @Override public void checkWrite(FileDescriptor fd) { if (originalSecurityManager != null) { originalSecurityManager.checkWrite(fd); } } @Override public void checkWrite(String file) { if (originalSecurityManager != null) { originalSecurityManager.checkWrite(file); } } @Override public void checkDelete(String file) { if (originalSecurityManager != null) { originalSecurityManager.checkDelete(file); } } @Override public void checkConnect(String host, int port) { if (originalSecurityManager != null) { originalSecurityManager.checkConnect(host, port); } } @Override public void checkConnect(String host, int port, Object context) { if (originalSecurityManager != null) { originalSecurityManager.checkConnect(host, port, context); } } @Override public void checkListen(int port) { if (originalSecurityManager != null) { originalSecurityManager.checkListen(port); } } @Override public void checkAccept(String host, int port) { if (originalSecurityManager != null) { originalSecurityManager.checkAccept(host, port); } } @Override public void checkMulticast(InetAddress maddr) { if (originalSecurityManager != null) { originalSecurityManager.checkMulticast(maddr); } } @Override public void checkMulticast(InetAddress maddr, byte ttl) { if (originalSecurityManager != null) { originalSecurityManager.checkMulticast(maddr, ttl); } } @Override public void checkPropertiesAccess() { if (originalSecurityManager != null) { originalSecurityManager.checkPropertiesAccess(); } } @Override public void checkPropertyAccess(String key) { if (originalSecurityManager != null) { originalSecurityManager.checkPropertyAccess(key); } } @Override public boolean checkTopLevelWindow(Object window) { return (originalSecurityManager == null) ? super.checkTopLevelWindow(window) : originalSecurityManager.checkTopLevelWindow(window); } @Override public void checkPrintJobAccess() { if (originalSecurityManager != null) { originalSecurityManager.checkPrintJobAccess(); } } @Override public void checkSystemClipboardAccess() { if (originalSecurityManager != null) { originalSecurityManager.checkSystemClipboardAccess(); } } @Override public void checkAwtEventQueueAccess() { if (originalSecurityManager != null) { originalSecurityManager.checkAwtEventQueueAccess(); } } @Override public void checkPackageAccess(String pkg) { if (originalSecurityManager != null) { originalSecurityManager.checkPackageAccess(pkg); } } @Override public void checkPackageDefinition(String pkg) { if (originalSecurityManager != null) { originalSecurityManager.checkPackageDefinition(pkg); } } @Override public void checkSetFactory() { if (originalSecurityManager != null) { originalSecurityManager.checkSetFactory(); } } @Override public void checkMemberAccess(Class clazz, int which) { if (originalSecurityManager != null) { originalSecurityManager.checkMemberAccess(clazz, which); } } @Override public void checkSecurityAccess(String target) { if (originalSecurityManager != null) { originalSecurityManager.checkSecurityAccess(target); } } @Override public ThreadGroup getThreadGroup() { return (originalSecurityManager == null) ? super.getThreadGroup() : originalSecurityManager.getThreadGroup(); } } /** * Execute runnable.run(), preventing System.exit(). If System.exit() is called * in runnable.run(), the value is returned. If System.exit() * is not called, null is returned. * * @return null if System.exit() is not called, Integer.valueof(status) if not */ public Integer runWithCheckForSystemExit(Runnable runnable) { SecurityManager oldSecurityManager = System.getSecurityManager(); System.setSecurityManager(new NoExitSecurityManager(oldSecurityManager)); PrintStream oldPrintStream = System.out; System.setOut(new PrintStream(new ByteArrayOutputStream())); try { runnable.run(); System.out.println("System.exit() not called, return null"); return null; } catch (ExitException e) { System.out.println("System.exit() called, value=" + e.getStatus()); return e.getStatus(); } finally { System.setSecurityManager(oldSecurityManager); System.setOut(oldPrintStream); } } } junit4-4.11/src/test/java/org/junit/tests/running/core/JUnitCoreReturnsCorrectExitCodeTest.java0000644000175000017500000000220512050524441032260 0ustar ebourgebourgpackage org.junit.tests.running.core; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.junit.Test; import org.junit.runner.JUnitCore; public class JUnitCoreReturnsCorrectExitCodeTest { static public class Fail { @Test public void kaboom() { fail(); } } @Test public void failureCausesExitCodeOf1() throws Exception { runClass(getClass().getName() + "$Fail", 1); } @Test public void missingClassCausesExitCodeOf1() throws Exception { runClass("Foo", 1); } static public class Succeed { @Test public void peacefulSilence() { } } @Test public void successCausesExitCodeOf0() throws Exception { runClass(getClass().getName() + "$Succeed", 0); } private void runClass(final String className, int returnCode) { Integer exitValue = new MainRunner().runWithCheckForSystemExit(new Runnable() { public void run() { JUnitCore.main(className); } }); assertEquals(Integer.valueOf(returnCode), exitValue); } } junit4-4.11/src/test/java/org/junit/tests/running/core/SystemExitTest.java0000644000175000017500000000206212050524441026203 0ustar ebourgebourgpackage org.junit.tests.running.core; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.InputStream; import org.junit.Test; // Make sure System.exit works as expected. We've had problems with this on some platforms. public class SystemExitTest { private static final int EXIT_CODE = 5; static public class Exit { public static void main(String[] args) { System.exit(EXIT_CODE); } } @Test public void failureCausesExitCodeOf1() throws Exception { String java = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"; String classPath = getClass().getClassLoader().getResource(".").getFile() + File.pathSeparator + System.getProperty("java.class.path"); String[] cmd = {java, "-cp", classPath, getClass().getName() + "$Exit"}; Process process = Runtime.getRuntime().exec(cmd); InputStream input = process.getInputStream(); while ((input.read()) != -1) ; assertEquals(EXIT_CODE, process.waitFor()); } } junit4-4.11/src/test/java/org/junit/tests/assertion/0000755000175000017500000000000012050524441021761 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/assertion/MultipleFailureExceptionTest.java0000644000175000017500000000372412050524441030454 0ustar ebourgebourg// Copyright 2010 Google Inc. All Rights Reserved. package org.junit.tests.assertion; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.Test; import org.junit.runners.model.MultipleFailureException; /** * Tests for {@link org.junit.runners.model.MultipleFailureException} * * @author kcooney@google.com (Kevin Cooney) */ public class MultipleFailureExceptionTest { @Test public void assertEmptyDoesNotThrowForEmptyList() throws Throwable { MultipleFailureException.assertEmpty(Collections.emptyList()); } @Test(expected = ExpectedException.class) public void assertEmptyRethrowsSingleThrowable() throws Throwable { MultipleFailureException.assertEmpty( Collections.singletonList(new ExpectedException("pesto"))); } @Test public void assertEmptyThrowsMutipleFailureExceptionForManyThrowables() throws Throwable { List errors = new ArrayList(); errors.add(new ExpectedException("basil")); errors.add(new RuntimeException("garlic")); try { MultipleFailureException.assertEmpty(errors); fail(); } catch (MultipleFailureException expected) { assertThat(expected.getFailures(), equalTo(errors)); assertTrue(expected.getMessage().startsWith("There were 2 errors:\n")); assertTrue(expected.getMessage().contains("ExpectedException(basil)\n")); assertTrue(expected.getMessage().contains("RuntimeException(garlic)")); } } private static class ExpectedException extends RuntimeException { private static final long serialVersionUID = 1L; public ExpectedException(String message) { super(message); } } } junit4-4.11/src/test/java/org/junit/tests/assertion/AssertionTest.java0000644000175000017500000004560312050524441025443 0ustar ebourgebourgpackage org.junit.tests.assertion; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotSame; 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 java.math.BigDecimal; import org.junit.Assert; import org.junit.ComparisonFailure; import org.junit.Test; import org.junit.internal.ArrayComparisonFailure; /** * Tests for {@link org.junit.Assert} */ public class AssertionTest { // If you want to use 1.4 assertions, they will be reported correctly. // However, you need to add the -ea VM argument when running. // @Test (expected=AssertionError.class) public void error() { // assert false; // } @Test(expected = AssertionError.class) public void fails() { Assert.fail(); } @Test public void failWithNoMessageToString() { try { Assert.fail(); } catch (AssertionError exception) { assertEquals("java.lang.AssertionError", exception.toString()); } } @Test public void failWithMessageToString() { try { Assert.fail("woops!"); } catch (AssertionError exception) { assertEquals("java.lang.AssertionError: woops!", exception.toString()); } } @Test(expected = AssertionError.class) public void arraysNotEqual() { assertArrayEquals((new Object[]{new Object()}), (new Object[]{new Object()})); } @Test(expected = AssertionError.class) public void arraysNotEqualWithMessage() { assertArrayEquals("not equal", (new Object[]{new Object()}), (new Object[]{new Object()})); } @Test public void arraysExpectedNullMessage() { try { assertArrayEquals("not equal", null, (new Object[]{new Object()})); } catch (AssertionError exception) { assertEquals("not equal: expected array was null", exception.getMessage()); } } @Test public void arraysActualNullMessage() { try { assertArrayEquals("not equal", (new Object[]{new Object()}), null); } catch (AssertionError exception) { assertEquals("not equal: actual array was null", exception.getMessage()); } } @Test public void arraysDifferentLengthMessage() { try { assertArrayEquals("not equal", (new Object[0]), (new Object[1])); } catch (AssertionError exception) { assertEquals("not equal: array lengths differed, expected.length=0 actual.length=1", exception.getMessage()); } } @Test(expected = ArrayComparisonFailure.class) public void arraysElementsDiffer() { assertArrayEquals("not equal", (new Object[]{"this is a very long string in the middle of an array"}), (new Object[]{"this is another very long string in the middle of an array"})); } @Test public void arraysDifferAtElement0nullMessage() { try { assertArrayEquals((new Object[]{true}), (new Object[]{false})); } catch (AssertionError exception) { assertEquals("arrays first differed at element [0]; expected: but was:", exception .getMessage()); } } @Test public void arraysDifferAtElement1nullMessage() { try { assertArrayEquals((new Object[]{true, true}), (new Object[]{true, false})); } catch (AssertionError exception) { assertEquals("arrays first differed at element [1]; expected: but was:", exception .getMessage()); } } @Test public void arraysDifferAtElement0withMessage() { try { assertArrayEquals("message", (new Object[]{true}), (new Object[]{false})); } catch (AssertionError exception) { assertEquals("message: arrays first differed at element [0]; expected: but was:", exception .getMessage()); } } @Test public void arraysDifferAtElement1withMessage() { try { assertArrayEquals("message", (new Object[]{true, true}), (new Object[]{true, false})); fail(); } catch (AssertionError exception) { assertEquals("message: arrays first differed at element [1]; expected: but was:", exception.getMessage()); } } @Test public void multiDimensionalArraysAreEqual() { assertArrayEquals((new Object[][]{{true, true}, {false, false}}), (new Object[][]{{true, true}, {false, false}})); } @Test public void multiDimensionalIntArraysAreEqual() { int[][] int1 = {{1, 2, 3}, {4, 5, 6}}; int[][] int2 = {{1, 2, 3}, {4, 5, 6}}; assertArrayEquals(int1, int2); } @Test public void oneDimensionalPrimitiveArraysAreEqual() { assertArrayEquals(new byte[]{1}, new byte[]{1}); assertArrayEquals(new char[]{1}, new char[]{1}); assertArrayEquals(new short[]{1}, new short[]{1}); assertArrayEquals(new int[]{1}, new int[]{1}); assertArrayEquals(new long[]{1}, new long[]{1}); assertArrayEquals(new double[]{1.0}, new double[]{1.0}, 1.0); assertArrayEquals(new float[]{1.0f}, new float[]{1.0f}, 1.0f); } @Test(expected = AssertionError.class) public void oneDimensionalDoubleArraysAreNotEqual() { assertArrayEquals(new double[]{1.0}, new double[]{2.5}, 1.0); } @Test(expected = AssertionError.class) public void oneDimensionalFloatArraysAreNotEqual() { assertArrayEquals(new float[]{1.0f}, new float[]{2.5f}, 1.0f); } @Test(expected = AssertionError.class) public void IntegerDoesNotEqualLong() { assertEquals(new Integer(1), new Long(1)); } @Test public void intsEqualLongs() { assertEquals(1, 1L); } @Test public void multiDimensionalArraysDeclaredAsOneDimensionalAreEqual() { assertArrayEquals((new Object[]{new Object[]{true, true}, new Object[]{false, false}}), (new Object[]{new Object[]{true, true}, new Object[]{false, false}})); } @Test public void multiDimensionalArraysAreNotEqual() { try { assertArrayEquals("message", (new Object[][]{{true, true}, {false, false}}), (new Object[][]{{true, true}, {true, false}})); fail(); } catch (AssertionError exception) { assertEquals("message: arrays first differed at element [1][0]; expected: but was:", exception.getMessage()); } } @Test public void multiDimensionalArraysAreNotEqualNoMessage() { try { assertArrayEquals((new Object[][]{{true, true}, {false, false}}), (new Object[][]{{true, true}, {true, false}})); fail(); } catch (AssertionError exception) { assertEquals("arrays first differed at element [1][0]; expected: but was:", exception.getMessage()); } } @Test public void arraysWithNullElementEqual() { Object[] objects1 = new Object[]{null}; Object[] objects2 = new Object[]{null}; assertArrayEquals(objects1, objects2); } @Test public void stringsDifferWithUserMessage() { try { assertEquals("not equal", "one", "two"); } catch (Throwable exception) { assertEquals("not equal expected:<[one]> but was:<[two]>", exception.getMessage()); } } @Test public void arraysEqual() { Object element = new Object(); Object[] objects1 = new Object[]{element}; Object[] objects2 = new Object[]{element}; assertArrayEquals(objects1, objects2); } @Test public void arraysEqualWithMessage() { Object element = new Object(); Object[] objects1 = new Object[]{element}; Object[] objects2 = new Object[]{element}; assertArrayEquals("equal", objects1, objects2); } @Test public void equals() { Object o = new Object(); assertEquals(o, o); assertEquals("abc", "abc"); assertEquals(true, true); assertEquals((byte) 1, (byte) 1); assertEquals('a', 'a'); assertEquals((short) 1, (short) 1); assertEquals(1, 1); // int by default, cast is unnecessary assertEquals(1l, 1l); assertEquals(1.0, 1.0, 0.0); assertEquals(1.0d, 1.0d, 0.0d); } @Test(expected = AssertionError.class) public void notEqualsObjectWithNull() { assertEquals(new Object(), null); } @Test(expected = AssertionError.class) public void notEqualsNullWithObject() { assertEquals(null, new Object()); } @Test public void notEqualsObjectWithNullWithMessage() { Object o = new Object(); try { assertEquals("message", null, o); fail(); } catch (AssertionError e) { assertEquals("message expected: but was:<" + o.toString() + ">", e.getMessage()); } } @Test public void notEqualsNullWithObjectWithMessage() { Object o = new Object(); try { assertEquals("message", o, null); fail(); } catch (AssertionError e) { assertEquals("message expected:<" + o.toString() + "> but was:", e.getMessage()); } } @Test(expected = AssertionError.class) public void objectsNotEquals() { assertEquals(new Object(), new Object()); } @Test(expected = ComparisonFailure.class) public void stringsNotEqual() { assertEquals("abc", "def"); } @Test(expected = AssertionError.class) public void booleansNotEqual() { assertEquals(true, false); } @Test(expected = AssertionError.class) public void bytesNotEqual() { assertEquals((byte) 1, (byte) 2); } @Test(expected = AssertionError.class) public void charsNotEqual() { assertEquals('a', 'b'); } @Test(expected = AssertionError.class) public void shortsNotEqual() { assertEquals((short) 1, (short) 2); } @Test(expected = AssertionError.class) public void intsNotEqual() { assertEquals(1, 2); } @Test(expected = AssertionError.class) public void longsNotEqual() { assertEquals(1l, 2l); } @Test(expected = AssertionError.class) public void floatsNotEqual() { assertEquals(1.0, 2.0, 0.9); } @SuppressWarnings("deprecation") @Test(expected = AssertionError.class) public void floatsNotEqualWithoutDelta() { assertEquals(1.0, 1.1); } @Test public void floatsNotDoublesInArrays() { float delta = 4.444f; float[] f1 = new float[]{1.111f}; float[] f2 = new float[]{5.555f}; Assert.assertArrayEquals(f1, f2, delta); } @Test(expected = AssertionError.class) public void bigDecimalsNotEqual() { assertEquals(new BigDecimal("123.4"), new BigDecimal("123.0")); } @Test(expected = AssertionError.class) public void doublesNotEqual() { assertEquals(1.0d, 2.0d, 0.9d); } @Test public void naNsAreEqual() { assertEquals(Float.NaN, Float.NaN, Float.POSITIVE_INFINITY); assertEquals(Double.NaN, Double.NaN, Double.POSITIVE_INFINITY); } @Test public void nullNullmessage() { try { assertNull("junit"); fail(); } catch (AssertionError e) { assertEquals("expected null, but was:", e.getMessage()); } } @Test public void nullWithMessage() { try { assertNull("message", "hello"); fail(); } catch (AssertionError exception) { assertEquals("message expected null, but was:", exception.getMessage()); } } @Test public void same() { Object o1 = new Object(); assertSame(o1, o1); } @Test public void notSame() { Object o1 = new Object(); Object o2 = new Object(); assertNotSame(o1, o2); } @Test(expected = AssertionError.class) public void objectsNotSame() { assertSame(new Object(), new Object()); } @Test(expected = AssertionError.class) public void objectsAreSame() { Object o = new Object(); assertNotSame(o, o); } @Test public void sameWithMessage() { try { assertSame("not same", "hello", "good-bye"); fail(); } catch (AssertionError exception) { assertEquals("not same expected same: was not:", exception.getMessage()); } } @Test public void sameNullMessage() { try { assertSame("hello", "good-bye"); fail(); } catch (AssertionError exception) { assertEquals("expected same: was not:", exception.getMessage()); } } @Test public void notSameWithMessage() { Object o = new Object(); try { assertNotSame("message", o, o); fail(); } catch (AssertionError exception) { assertEquals("message expected not same", exception.getMessage()); } } @Test public void notSameNullMessage() { Object o = new Object(); try { assertNotSame(o, o); fail(); } catch (AssertionError exception) { assertEquals("expected not same", exception.getMessage()); } } @Test public void nullMessage() { try { fail(null); } catch (AssertionError exception) { // we used to expect getMessage() to return ""; see failWithNoMessageToString() assertNull(exception.getMessage()); } } @Test public void nullMessageDisappearsWithStringAssertEquals() { try { assertEquals(null, "a", "b"); fail(); } catch (ComparisonFailure e) { assertEquals("expected:<[a]> but was:<[b]>", e.getMessage()); } } @Test public void nullMessageDisappearsWithAssertEquals() { try { assertEquals(null, 1, 2); fail(); } catch (AssertionError e) { assertEquals("expected:<1> but was:<2>", e.getMessage()); } } @Test(expected = AssertionError.class) public void arraysDeclaredAsObjectAreComparedAsObjects() { Object a1 = new Object[]{"abc"}; Object a2 = new Object[]{"abc"}; assertEquals(a1, a2); } @Test public void implicitTypecastEquality() { byte b = 1; short s = 1; int i = 1; long l = 1L; float f = 1.0f; double d = 1.0; assertEquals(b, s); assertEquals(b, i); assertEquals(b, l); assertEquals(s, i); assertEquals(s, l); assertEquals(i, l); assertEquals(f, d, 0); } @Test public void errorMessageDistinguishesDifferentValuesWithSameToString() { try { assertEquals("4", new Integer(4)); } catch (AssertionError e) { assertEquals("expected: java.lang.String<4> but was: java.lang.Integer<4>", e.getMessage()); } } @Test public void assertThatIncludesDescriptionOfTestedValueInErrorMessage() { String expected = "expected"; String actual = "actual"; String expectedMessage = "identifier\nExpected: \"expected\"\n but: was \"actual\""; try { assertThat("identifier", actual, equalTo(expected)); } catch (AssertionError e) { assertEquals(expectedMessage, e.getMessage()); } } @Test public void assertThatIncludesAdvancedMismatch() { String expectedMessage = "identifier\nExpected: is an instance of java.lang.Integer\n but: \"actual\" is a java.lang.String"; try { assertThat("identifier", "actual", is(instanceOf(Integer.class))); } catch (AssertionError e) { assertEquals(expectedMessage, e.getMessage()); } } @Test public void assertThatDescriptionCanBeElided() { String expected = "expected"; String actual = "actual"; String expectedMessage = "\nExpected: \"expected\"\n but: was \"actual\""; try { assertThat(actual, equalTo(expected)); } catch (AssertionError e) { assertEquals(expectedMessage, e.getMessage()); } } @Test public void nullAndStringNullPrintCorrectError() { try { assertEquals(null, "null"); } catch (AssertionError e) { assertEquals("expected: null but was: java.lang.String", e.getMessage()); } } @Test(expected = AssertionError.class) public void stringNullAndNullWorksToo() { assertEquals("null", null); } @Test(expected = AssertionError.class) public void compareBigDecimalAndInteger() { final BigDecimal bigDecimal = new BigDecimal("1.2"); final Integer integer = Integer.valueOf("1"); assertEquals(bigDecimal, integer); } @Test(expected = AssertionError.class) public void sameObjectIsNotEqual() { Object o = new Object(); assertNotEquals(o, o); } @Test public void objectsWithDiferentReferencesAreNotEqual() { assertNotEquals(new Object(), new Object()); } @Test public void assertNotEqualsIncludesCorrectMessage() { Integer value1 = new Integer(1); Integer value2 = new Integer(1); String message = "The values should be different"; try { assertNotEquals(message, value1, value2); } catch (AssertionError e) { assertEquals(message + ". Actual: " + value1, e.getMessage()); return; } fail("Failed on assertion."); } @Test public void assertNotEqualsIncludesTheValueBeingTested() { Integer value1 = new Integer(1); Integer value2 = new Integer(1); try { assertNotEquals(value1, value2); } catch (AssertionError e) { assertTrue(e.getMessage().contains(value1.toString())); return; } fail("Failed on assertion."); } @Test public void assertNotEqualsWorksWithPrimitiveTypes() { assertNotEquals(1L, 2L); assertNotEquals("The values should be different", 1L, 2L); assertNotEquals(1.0, 2.0, 0); assertNotEquals("The values should be different", 1.0, 2.0, 0); } @Test(expected = AssertionError.class) public void assertNotEqualsConsidersDeltaCorrectly() { assertNotEquals(1.0, 0.9, 0.1); } @Test(expected = AssertionError.class) public void assertNotEqualsIgnoresDeltaOnNaN() { assertNotEquals(Double.NaN, Double.NaN, 1); } } junit4-4.11/src/test/java/org/junit/tests/junit3compatibility/0000755000175000017500000000000012050524441023760 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/tests/junit3compatibility/ForwardCompatibilityPrintingTest.java0000644000175000017500000000570512050524441033343 0ustar ebourgebourgpackage org.junit.tests.junit3compatibility; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.io.PrintStream; import junit.framework.JUnit4TestAdapter; import junit.framework.TestCase; import junit.framework.TestResult; import junit.framework.TestSuite; import junit.textui.ResultPrinter; import junit.textui.TestRunner; import org.junit.Assert; import org.junit.Test; public class ForwardCompatibilityPrintingTest extends TestCase { static class TestResultPrinter extends ResultPrinter { TestResultPrinter(PrintStream writer) { super(writer); } /* * Spoof printing time so the tests are deterministic */ @Override protected String elapsedTimeAsString(long runTime) { return "0"; } } public void testError() { ByteArrayOutputStream output = new ByteArrayOutputStream(); TestRunner runner = new TestRunner(new TestResultPrinter( new PrintStream(output))); String expected = expected(new String[]{".E", "Time: 0", "Errors here", "", "FAILURES!!!", "Tests run: 1, Failures: 0, Errors: 1", ""}); ResultPrinter printer = new TestResultPrinter(new PrintStream(output)) { @Override public void printErrors(TestResult result) { getWriter().println("Errors here"); } }; runner.setPrinter(printer); TestSuite suite = new TestSuite(); suite.addTest(new TestCase() { @Override public void runTest() throws Exception { throw new Exception(); } }); runner.doRun(suite); assertEquals(expected, output.toString()); } public static class ATest { @Test public void error() { Assert.fail(); } } public void testErrorAdapted() { ByteArrayOutputStream output = new ByteArrayOutputStream(); TestRunner runner = new TestRunner(new TestResultPrinter( new PrintStream(output))); String expected = expected(new String[]{".E", "Time: 0", "Errors here", "", "FAILURES!!!", "Tests run: 1, Failures: 0, Errors: 1", ""}); ResultPrinter printer = new TestResultPrinter(new PrintStream(output)) { @Override public void printErrors(TestResult result) { getWriter().println("Errors here"); } }; runner.setPrinter(printer); runner.doRun(new JUnit4TestAdapter(ATest.class)); assertEquals(expected, output.toString()); } private String expected(String[] lines) { OutputStream expected = new ByteArrayOutputStream(); PrintStream expectedWriter = new PrintStream(expected); for (int i = 0; i < lines.length; i++) { expectedWriter.println(lines[i]); } return expected.toString(); } } junit4-4.11/src/test/java/org/junit/tests/junit3compatibility/OldTests.java0000644000175000017500000000042712050524441026367 0ustar ebourgebourgpackage org.junit.tests.junit3compatibility; import junit.framework.Test; import org.junit.runner.RunWith; import org.junit.runners.AllTests; @RunWith(AllTests.class) public class OldTests { static public Test suite() { return junit.tests.AllTests.suite(); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootjunit4-4.11/src/test/java/org/junit/tests/junit3compatibility/InitializationErrorForwardCompatibilityTest.javajunit4-4.11/src/test/java/org/junit/tests/junit3compatibility/InitializationErrorForwardCompatibilit0000644000175000017500000000576212050524441033604 0ustar ebourgebourgpackage org.junit.tests.junit3compatibility; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import junit.framework.AssertionFailedError; import junit.framework.JUnit4TestAdapter; import junit.framework.TestListener; import junit.framework.TestResult; import org.junit.Before; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.RunWith; import org.junit.runner.Runner; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; public class InitializationErrorForwardCompatibilityTest { public static class CantInitialize extends Runner { private static final String UNIQUE_ERROR_MESSAGE = "Unique error message"; public CantInitialize(Class klass) throws Exception { throw new Exception(UNIQUE_ERROR_MESSAGE); } @Override public Description getDescription() { return Description.EMPTY; } @Override public void run(RunNotifier notifier) { } } @RunWith(CantInitialize.class) public static class CantInitializeTests { } private JUnit4TestAdapter fAdapter; @Before public void createAdapter() { fAdapter = new JUnit4TestAdapter( CantInitializeTests.class); } @Test public void initializationErrorsShowUpAsWarnings() { assertEquals(1, fAdapter.getTests().size()); } @Test public void initializationErrorsAreThrownAtRuntime() { TestResult result = new TestResult(); fAdapter.run(result); assertEquals(1, result.errorCount()); assertEquals(CantInitialize.UNIQUE_ERROR_MESSAGE, result.errors() .nextElement().exceptionMessage()); } private final class ErrorRememberingListener implements TestListener { private junit.framework.Test fError; public void addError(junit.framework.Test test, Throwable t) { fError = test; } public void addFailure(junit.framework.Test test, AssertionFailedError t) { } public void endTest(junit.framework.Test test) { } public void startTest(junit.framework.Test test) { } public junit.framework.Test getError() { return fError; } } @Test public void generatedErrorTestsMatchUp() { junit.framework.Test shouldFail = fAdapter.getTests().get(0); TestResult result = new TestResult(); ErrorRememberingListener listener = new ErrorRememberingListener(); result.addListener(listener); fAdapter.run(result); assertNotNull(listener.getError()); assertTrue(shouldFail == listener.getError()); } public static class InitializesWithError extends BlockJUnit4ClassRunner { public InitializesWithError(Class klass) throws Exception { super(klass); throw new Exception(); } } } junit4-4.11/src/test/java/org/junit/tests/junit3compatibility/AllTestsTest.java0000644000175000017500000000474612050524441027231 0ustar ebourgebourgpackage org.junit.tests.junit3compatibility; import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import junit.framework.JUnit4TestAdapter; import junit.framework.TestCase; import junit.framework.TestSuite; import org.junit.runner.JUnitCore; import org.junit.runner.RunWith; import org.junit.runners.AllTests; public class AllTestsTest { private static boolean run; public static class OneTest extends TestCase { public void testSomething() { run = true; } } @RunWith(AllTests.class) public static class All { static public junit.framework.Test suite() { TestSuite suite = new TestSuite(); suite.addTestSuite(OneTest.class); return suite; } } @org.junit.Test public void ensureTestIsRun() { JUnitCore runner = new JUnitCore(); run = false; // Have to explicitly set run here because the runner might independently run OneTest above runner.run(All.class); assertTrue(run); } @org.junit.Test public void correctTestCount() throws Throwable { AllTests tests = new AllTests(All.class); assertEquals(1, tests.testCount()); } @org.junit.Test public void someUsefulDescription() throws Throwable { AllTests tests = new AllTests(All.class); assertThat(tests.getDescription().toString(), containsString("OneTest")); } public static class JUnit4Test { @org.junit.Test public void testSomething() { run = true; } } @RunWith(AllTests.class) public static class AllJUnit4 { static public junit.framework.Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new JUnit4TestAdapter(JUnit4Test.class)); return suite; } } @org.junit.Test public void correctTestCountAdapted() throws Throwable { AllTests tests = new AllTests(AllJUnit4.class); assertEquals(1, tests.testCount()); } @RunWith(AllTests.class) public static class BadSuiteMethod { public static junit.framework.Test suite() { throw new RuntimeException("can't construct"); } } @org.junit.Test(expected = RuntimeException.class) public void exceptionThrownWhenSuiteIsBad() throws Throwable { new AllTests(BadSuiteMethod.class); } } junit4-4.11/src/test/java/org/junit/tests/junit3compatibility/OldTestClassAdaptingListenerTest.java0000644000175000017500000000200412050524441033201 0ustar ebourgebourgpackage org.junit.tests.junit3compatibility; import static org.junit.Assert.assertEquals; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import junit.framework.TestListener; import org.junit.Test; import org.junit.internal.runners.JUnit38ClassRunner; import org.junit.runner.Result; import org.junit.runner.notification.RunListener; import org.junit.runner.notification.RunNotifier; public class OldTestClassAdaptingListenerTest { @Test public void addFailureDelegatesToNotifier() { Result result = new Result(); RunListener listener = result.createListener(); RunNotifier notifier = new RunNotifier(); notifier.addFirstListener(listener); TestCase testCase = new TestCase() { }; TestListener adaptingListener = new JUnit38ClassRunner(testCase) .createAdaptingListener(notifier); adaptingListener.addFailure(testCase, new AssertionFailedError()); assertEquals(1, result.getFailureCount()); } } junit4-4.11/src/test/java/org/junit/tests/junit3compatibility/JUnit38ClassRunnerTest.java0000644000175000017500000000515112050524441031051 0ustar ebourgebourgpackage org.junit.tests.junit3compatibility; import static org.junit.Assert.assertEquals; import junit.extensions.TestDecorator; import junit.framework.JUnit4TestAdapter; import junit.framework.TestCase; import junit.framework.TestSuite; import org.junit.Assert; import org.junit.Test; import org.junit.internal.runners.JUnit38ClassRunner; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; public class JUnit38ClassRunnerTest { public static class MyTest extends TestCase { public void testA() { } } @Test public void plansDecoratorCorrectly() { JUnit38ClassRunner runner = new JUnit38ClassRunner(new TestDecorator(new TestSuite(MyTest.class))); assertEquals(1, runner.testCount()); } public static class AnnotatedTest { @Test public void foo() { Assert.fail(); } } @Test public void canUnadaptAnAdapter() { JUnit38ClassRunner runner = new JUnit38ClassRunner(new JUnit4TestAdapter(AnnotatedTest.class)); Result result = new JUnitCore().run(runner); Failure failure = result.getFailures().get(0); assertEquals(Description.createTestDescription(AnnotatedTest.class, "foo"), failure.getDescription()); } static int count; static public class OneTest extends TestCase { public void testOne() { } } @Test public void testListener() throws Exception { JUnitCore runner = new JUnitCore(); RunListener listener = new RunListener() { @Override public void testStarted(Description description) { assertEquals(Description.createTestDescription(OneTest.class, "testOne"), description); count++; } }; runner.addListener(listener); count = 0; Result result = runner.run(OneTest.class); assertEquals(1, count); assertEquals(1, result.getRunCount()); } public static class ClassWithInvalidMethod extends TestCase { @SuppressWarnings("unused") private void testInvalid() { } } @Test public void invalidTestMethodReportedCorrectly() { Result result = JUnitCore.runClasses(ClassWithInvalidMethod.class); Failure failure = result.getFailures().get(0); assertEquals("warning", failure.getDescription().getMethodName()); assertEquals("junit.framework.TestSuite$1", failure.getDescription().getClassName()); } } junit4-4.11/src/test/java/org/junit/tests/junit3compatibility/ClassRequestTest.java0000644000175000017500000000101212050524441030073 0ustar ebourgebourgpackage org.junit.tests.junit3compatibility; import static org.junit.Assert.assertNull; import org.junit.Test; import org.junit.internal.builders.SuiteMethodBuilder; public class ClassRequestTest { public static class PrivateSuiteMethod { static junit.framework.Test suite() { return null; } } @Test public void noSuiteMethodIfMethodPrivate() throws Throwable { assertNull(new SuiteMethodBuilder() .runnerForClass(PrivateSuiteMethod.class)); } } junit4-4.11/src/test/java/org/junit/tests/junit3compatibility/SuiteMethodTest.java0000644000175000017500000000706712050524441027727 0ustar ebourgebourgpackage org.junit.tests.junit3compatibility; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import junit.framework.JUnit4TestAdapter; import junit.framework.TestCase; import junit.framework.TestSuite; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.Request; import org.junit.runner.Result; public class SuiteMethodTest { public static boolean wasRun; static public class OldTest extends TestCase { public OldTest(String name) { super(name); } public static junit.framework.Test suite() { TestSuite result = new TestSuite(); result.addTest(new OldTest("notObviouslyATest")); return result; } public void notObviouslyATest() { wasRun = true; } } @Test public void makeSureSuiteIsCalled() { wasRun = false; JUnitCore.runClasses(OldTest.class); assertTrue(wasRun); } static public class NewTest { @Test public void sample() { wasRun = true; } public static junit.framework.Test suite() { return new JUnit4TestAdapter(NewTest.class); } } @Test public void makeSureSuiteWorksWithJUnit4Classes() { wasRun = false; JUnitCore.runClasses(NewTest.class); assertTrue(wasRun); } public static class CompatibilityTest { @Ignore @Test public void ignored() { } public static junit.framework.Test suite() { return new JUnit4TestAdapter(CompatibilityTest.class); } } // when executing as JUnit 3, ignored tests are stripped out before execution @Test public void descriptionAndRunNotificationsAreConsistent() { Result result = JUnitCore.runClasses(CompatibilityTest.class); assertEquals(0, result.getIgnoreCount()); Description description = Request.aClass(CompatibilityTest.class).getRunner().getDescription(); assertEquals(0, description.getChildren().size()); } static public class NewTestSuiteFails { @Test public void sample() { wasRun = true; } public static junit.framework.Test suite() { fail("called with JUnit 4 runner"); return null; } } @Test public void suiteIsUsedWithJUnit4Classes() { wasRun = false; Result result = JUnitCore.runClasses(NewTestSuiteFails.class); assertEquals(1, result.getFailureCount()); assertFalse(wasRun); } static public class NewTestSuiteNotUsed { private static boolean wasIgnoredRun; @Test public void sample() { wasRun = true; } @Ignore @Test public void ignore() { wasIgnoredRun = true; } public static junit.framework.Test suite() { return new JUnit4TestAdapter(NewTestSuiteNotUsed.class); } } @Test public void makeSureSuiteNotUsedWithJUnit4Classes2() { wasRun = false; NewTestSuiteNotUsed.wasIgnoredRun = false; Result res = JUnitCore.runClasses(NewTestSuiteNotUsed.class); assertTrue(wasRun); assertFalse(NewTestSuiteNotUsed.wasIgnoredRun); assertEquals(0, res.getFailureCount()); assertEquals(1, res.getRunCount()); assertEquals(0, res.getIgnoreCount()); } } junit4-4.11/src/test/java/org/junit/tests/junit3compatibility/ForwardCompatibilityTest.java0000644000175000017500000001610012050524441031617 0ustar ebourgebourgpackage org.junit.tests.junit3compatibility; import junit.framework.AssertionFailedError; import junit.framework.JUnit4TestAdapter; import junit.framework.TestCase; import junit.framework.TestFailure; import junit.framework.TestListener; import junit.framework.TestResult; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.RunWith; import org.junit.runner.Runner; import org.junit.runner.notification.RunNotifier; public class ForwardCompatibilityTest extends TestCase { static String fLog; static public class NewTest { @Before public void before() { fLog += "before "; } @After public void after() { fLog += "after "; } @Test public void test() { fLog += "test "; } } public void testCompatibility() { fLog = ""; TestResult result = new TestResult(); junit.framework.Test adapter = new JUnit4TestAdapter(NewTest.class); adapter.run(result); assertEquals("before test after ", fLog); } public void testToString() { JUnit4TestAdapter adapter = new JUnit4TestAdapter(NewTest.class); junit.framework.Test test = adapter.getTests().get(0); assertEquals(String.format("test(%s)", NewTest.class.getName()), test.toString()); } public void testUseGlobalCache() { JUnit4TestAdapter adapter1 = new JUnit4TestAdapter(NewTest.class); JUnit4TestAdapter adapter2 = new JUnit4TestAdapter(NewTest.class); assertSame(adapter1.getTests().get(0), adapter2.getTests().get(0)); } static Exception exception = new Exception(); public static class ErrorTest { @Test public void error() throws Exception { throw exception; } } public void testException() { TestResult result = new TestResult(); junit.framework.Test adapter = new JUnit4TestAdapter(ErrorTest.class); adapter.run(result); assertEquals(exception, result.errors().nextElement().thrownException()); } public void testNotifyResult() { JUnit4TestAdapter adapter = new JUnit4TestAdapter(ErrorTest.class); TestResult result = new TestResult(); final StringBuffer log = new StringBuffer(); result.addListener(new TestListener() { public void startTest(junit.framework.Test test) { log.append(" start " + test); } public void endTest(junit.framework.Test test) { log.append(" end " + test); } public void addFailure(junit.framework.Test test, AssertionFailedError t) { log.append(" failure " + test); } public void addError(junit.framework.Test test, Throwable t) { log.append(" error " + test); } }); adapter.run(result); String testName = String.format("error(%s)", ErrorTest.class.getName()); assertEquals(String.format(" start %s error %s end %s", testName, testName, testName), log.toString()); } public static class NoExceptionTest { @Test(expected = Exception.class) public void succeed() throws Exception { } } public void testNoException() { TestResult result = new TestResult(); junit.framework.Test adapter = new JUnit4TestAdapter(NoExceptionTest.class); adapter.run(result); assertFalse(result.wasSuccessful()); } public static class ExpectedTest { @Test(expected = Exception.class) public void expected() throws Exception { throw new Exception(); } } public void testExpected() { TestResult result = new TestResult(); junit.framework.Test adapter = new JUnit4TestAdapter(ExpectedTest.class); adapter.run(result); assertTrue(result.wasSuccessful()); } public static class UnExpectedExceptionTest { @Test(expected = Exception.class) public void expected() throws Exception { throw new Error(); } } static String log; public static class BeforeClassTest { @BeforeClass public static void beforeClass() { log += "before class "; } @Before public void before() { log += "before "; } @Test public void one() { log += "test "; } @Test public void two() { log += "test "; } @After public void after() { log += "after "; } @AfterClass public static void afterClass() { log += "after class "; } } public void testBeforeAndAfterClass() { log = ""; TestResult result = new TestResult(); junit.framework.Test adapter = new JUnit4TestAdapter(BeforeClassTest.class); adapter.run(result); assertEquals("before class before test after before test after after class ", log); } public static class ExceptionInBeforeTest { @Before public void error() { throw new Error(); } @Test public void nothing() { } } public void testExceptionInBefore() { TestResult result = new TestResult(); junit.framework.Test adapter = new JUnit4TestAdapter(ExceptionInBeforeTest.class); adapter.run(result); assertEquals(1, result.errorCount()); } public static class InvalidMethodTest { @BeforeClass public void shouldBeStatic() { } @Test public void aTest() { } } public void testInvalidMethod() { TestResult result = new TestResult(); junit.framework.Test adapter = new JUnit4TestAdapter(InvalidMethodTest.class); adapter.run(result); assertEquals(1, result.errorCount()); TestFailure failure = result.errors().nextElement(); assertTrue(failure.exceptionMessage().contains("Method shouldBeStatic() should be static")); } private static boolean wasRun = false; public static class MarkerRunner extends Runner { public MarkerRunner(Class klass) { } @Override public void run(RunNotifier notifier) { wasRun = true; } @Override public int testCount() { return 0; } @Override public Description getDescription() { return Description.EMPTY; } } @RunWith(MarkerRunner.class) public static class NoTests { } public void testRunWithClass() { wasRun = false; TestResult result = new TestResult(); junit.framework.Test adapter = new JUnit4TestAdapter(NoTests.class); adapter.run(result); assertTrue(wasRun); } public void testToStringSuite() { junit.framework.Test adapter = new JUnit4TestAdapter(NoTests.class); assertEquals(NoTests.class.getName(), adapter.toString()); } } junit4-4.11/src/test/java/org/junit/tests/AllTests.java0000644000175000017500000001656012050524441022360 0ustar ebourgebourgpackage org.junit.tests; import junit.framework.JUnit4TestAdapter; import junit.framework.Test; import org.junit.internal.MethodSorterTest; import org.junit.internal.matchers.StacktracePrintingMatcherTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import org.junit.tests.assertion.AssertionTest; import org.junit.tests.assertion.MultipleFailureExceptionTest; import org.junit.tests.deprecated.JUnit4ClassRunnerTest; import org.junit.tests.description.AnnotatedDescriptionTest; import org.junit.tests.description.SuiteDescriptionTest; import org.junit.tests.description.TestDescriptionTest; import org.junit.tests.experimental.AssumptionTest; import org.junit.tests.experimental.AssumptionViolatedExceptionTest; import org.junit.tests.experimental.ExperimentalTests; import org.junit.tests.experimental.MatcherTest; import org.junit.tests.experimental.categories.CategoriesAndParameterizedTest; import org.junit.tests.experimental.categories.CategoryTest; import org.junit.tests.experimental.max.JUnit38SortingTest; import org.junit.tests.experimental.max.MaxStarterTest; import org.junit.tests.experimental.parallel.ParallelClassTest; import org.junit.tests.experimental.parallel.ParallelMethodTest; import org.junit.tests.experimental.rules.BlockJUnit4ClassRunnerOverrideTest; import org.junit.tests.experimental.rules.ClassRulesTest; import org.junit.tests.experimental.rules.ExpectedExceptionTest; import org.junit.tests.experimental.rules.ExternalResourceRuleTest; import org.junit.tests.experimental.rules.MethodRulesTest; import org.junit.tests.experimental.rules.NameRulesTest; import org.junit.tests.experimental.rules.RuleChainTest; import org.junit.tests.experimental.rules.RuleFieldValidatorTest; import org.junit.tests.experimental.rules.TempFolderRuleTest; import org.junit.tests.experimental.rules.TemporaryFolderUsageTest; import org.junit.tests.experimental.rules.TestRuleTest; import org.junit.tests.experimental.rules.TimeoutRuleTest; import org.junit.tests.experimental.rules.VerifierRuleTest; import org.junit.tests.experimental.theories.AllMembersSupplierTest; import org.junit.tests.experimental.theories.TestedOnSupplierTest; import org.junit.tests.experimental.theories.runner.TheoriesPerformanceTest; import org.junit.tests.junit3compatibility.AllTestsTest; import org.junit.tests.junit3compatibility.ClassRequestTest; import org.junit.tests.junit3compatibility.ForwardCompatibilityTest; import org.junit.tests.junit3compatibility.InitializationErrorForwardCompatibilityTest; import org.junit.tests.junit3compatibility.JUnit38ClassRunnerTest; import org.junit.tests.junit3compatibility.OldTestClassAdaptingListenerTest; import org.junit.tests.junit3compatibility.OldTests; import org.junit.tests.junit3compatibility.SuiteMethodTest; import org.junit.tests.listening.ListenerTest; import org.junit.tests.listening.RunnerTest; import org.junit.tests.listening.TestListenerTest; import org.junit.tests.listening.TextListenerTest; import org.junit.tests.listening.UserStopTest; import org.junit.tests.manipulation.FilterTest; import org.junit.tests.manipulation.FilterableTest; import org.junit.tests.manipulation.SingleMethodTest; import org.junit.tests.manipulation.SortableTest; import org.junit.tests.running.classes.BlockJUnit4ClassRunnerTest; import org.junit.tests.running.classes.EnclosedTest; import org.junit.tests.running.classes.IgnoreClassTest; import org.junit.tests.running.classes.ParameterizedTestTest; import org.junit.tests.running.classes.ParentRunnerFilteringTest; import org.junit.tests.running.classes.ParentRunnerTest; import org.junit.tests.running.classes.RunWithTest; import org.junit.tests.running.classes.SuiteTest; import org.junit.tests.running.classes.TestClassTest; import org.junit.tests.running.classes.UseSuiteAsASuperclassTest; import org.junit.tests.running.core.CommandLineTest; import org.junit.tests.running.core.JUnitCoreReturnsCorrectExitCodeTest; import org.junit.tests.running.core.SystemExitTest; import org.junit.tests.running.methods.AnnotationTest; import org.junit.tests.running.methods.ExpectedTest; import org.junit.tests.running.methods.InheritedTestTest; import org.junit.tests.running.methods.ParameterizedTestMethodTest; import org.junit.tests.running.methods.TestMethodTest; import org.junit.tests.running.methods.TimeoutTest; import org.junit.tests.validation.BadlyFormedClassesTest; import org.junit.tests.validation.FailedConstructionTest; import org.junit.tests.validation.InaccessibleBaseClassTest; import org.junit.tests.validation.ValidationTest; // These test files need to be cleaned. See // https://sourceforge.net/pm/task.php?func=detailtask&project_task_id=136507&group_id=15278&group_project_id=51407 @SuppressWarnings("deprecation") @RunWith(Suite.class) @SuiteClasses({ AssumptionTest.class, ClassRequestTest.class, ListenerTest.class, FailedConstructionTest.class, TestDescriptionTest.class, SuiteDescriptionTest.class, AllTestsTest.class, AnnotationTest.class, AssertionTest.class, CommandLineTest.class, ExpectedTest.class, MultipleFailureExceptionTest.class, ForwardCompatibilityTest.class, OldTests.class, ParameterizedTestTest.class, RunWithTest.class, RunnerTest.class, SuiteTest.class, TestListenerTest.class, TestMethodTest.class, TextListenerTest.class, TimeoutTest.class, EnclosedTest.class, ParameterizedTestMethodTest.class, InitializationErrorForwardCompatibilityTest.class, SingleMethodTest.class, ValidationTest.class, UserStopTest.class, SortableTest.class, JUnit38ClassRunnerTest.class, SystemExitTest.class, JUnitCoreReturnsCorrectExitCodeTest.class, InaccessibleBaseClassTest.class, SuiteMethodTest.class, BadlyFormedClassesTest.class, IgnoreClassTest.class, OldTestClassAdaptingListenerTest.class, AnnotatedDescriptionTest.class, AssumptionViolatedExceptionTest.class, ExperimentalTests.class, InheritedTestTest.class, TestClassTest.class, AllMembersSupplierTest.class, MatcherTest.class, ObjectContractTest.class, TheoriesPerformanceTest.class, JUnit4ClassRunnerTest.class, UseSuiteAsASuperclassTest.class, FilterableTest.class, FilterTest.class, MaxStarterTest.class, JUnit38SortingTest.class, MethodRulesTest.class, TestRuleTest.class, TimeoutRuleTest.class, ParallelClassTest.class, ParallelMethodTest.class, ParentRunnerTest.class, NameRulesTest.class, ClassRulesTest.class, ExpectedExceptionTest.class, TempFolderRuleTest.class, TemporaryFolderUsageTest.class, ExternalResourceRuleTest.class, VerifierRuleTest.class, CategoryTest.class, CategoriesAndParameterizedTest.class, ParentRunnerFilteringTest.class, BlockJUnit4ClassRunnerOverrideTest.class, RuleFieldValidatorTest.class, RuleChainTest.class, BlockJUnit4ClassRunnerTest.class, MethodSorterTest.class, TestedOnSupplierTest.class, StacktracePrintingMatcherTest.class }) public class AllTests { public static Test suite() { return new JUnit4TestAdapter(AllTests.class); } } junit4-4.11/src/test/java/org/junit/samples/0000755000175000017500000000000012050524441020254 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/samples/package-info.java0000644000175000017500000000013712050524441023444 0ustar ebourgebourg/** * Provides examples on how to use JUnit 4. * * @since 4.0 */ package org.junit.samples;junit4-4.11/src/test/java/org/junit/samples/money/0000755000175000017500000000000012050524441021403 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/samples/money/package-info.java0000644000175000017500000000020512050524441024567 0ustar ebourgebourg/** * JUnit v4.x Test for the Money example. * * @since 4.0 * @see junit.samples.money.Money */ package org.junit.samples.money;junit4-4.11/src/test/java/org/junit/samples/money/MoneyTest.java0000644000175000017500000001432412050524441024201 0ustar ebourgebourgpackage org.junit.samples.money; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import junit.framework.JUnit4TestAdapter; import junit.samples.money.IMoney; import junit.samples.money.Money; import junit.samples.money.MoneyBag; import org.junit.Before; import org.junit.Test; public class MoneyTest { private Money f12CHF; private Money f14CHF; private Money f7USD; private Money f21USD; private IMoney fMB1; private IMoney fMB2; public static junit.framework.Test suite() { return new JUnit4TestAdapter(MoneyTest.class); } @Before public void setUp() { f12CHF = new Money(12, "CHF"); f14CHF = new Money(14, "CHF"); f7USD = new Money(7, "USD"); f21USD = new Money(21, "USD"); fMB1 = MoneyBag.create(f12CHF, f7USD); fMB2 = MoneyBag.create(f14CHF, f21USD); } @Test public void testBagMultiply() { // {[12 CHF][7 USD]} *2 == {[24 CHF][14 USD]} IMoney expected = MoneyBag.create(new Money(24, "CHF"), new Money(14, "USD")); assertEquals(expected, fMB1.multiply(2)); assertEquals(fMB1, fMB1.multiply(1)); assertTrue(fMB1.multiply(0).isZero()); } @Test public void testBagNegate() { // {[12 CHF][7 USD]} negate == {[-12 CHF][-7 USD]} IMoney expected = MoneyBag.create(new Money(-12, "CHF"), new Money(-7, "USD")); assertEquals(expected, fMB1.negate()); } @Test public void testBagSimpleAdd() { // {[12 CHF][7 USD]} + [14 CHF] == {[26 CHF][7 USD]} IMoney expected = MoneyBag.create(new Money(26, "CHF"), new Money(7, "USD")); assertEquals(expected, fMB1.add(f14CHF)); } @Test public void testBagSubtract() { // {[12 CHF][7 USD]} - {[14 CHF][21 USD] == {[-2 CHF][-14 USD]} IMoney expected = MoneyBag.create(new Money(-2, "CHF"), new Money(-14, "USD")); assertEquals(expected, fMB1.subtract(fMB2)); } @Test public void testBagSumAdd() { // {[12 CHF][7 USD]} + {[14 CHF][21 USD]} == {[26 CHF][28 USD]} IMoney expected = MoneyBag.create(new Money(26, "CHF"), new Money(28, "USD")); assertEquals(expected, fMB1.add(fMB2)); } @Test public void testIsZero() { assertTrue(fMB1.subtract(fMB1).isZero()); assertTrue(MoneyBag.create(new Money(0, "CHF"), new Money(0, "USD")).isZero()); } @Test public void testMixedSimpleAdd() { // [12 CHF] + [7 USD] == {[12 CHF][7 USD]} IMoney expected = MoneyBag.create(f12CHF, f7USD); assertEquals(expected, f12CHF.add(f7USD)); } @Test public void testBagNotEquals() { IMoney bag = MoneyBag.create(f12CHF, f7USD); assertFalse(bag.equals(new Money(12, "DEM").add(f7USD))); } @Test public void testMoneyBagEquals() { assertTrue(!fMB1.equals(null)); assertEquals(fMB1, fMB1); IMoney equal = MoneyBag.create(new Money(12, "CHF"), new Money(7, "USD")); assertTrue(fMB1.equals(equal)); assertTrue(!fMB1.equals(f12CHF)); assertTrue(!f12CHF.equals(fMB1)); assertTrue(!fMB1.equals(fMB2)); } @Test public void testMoneyBagHash() { IMoney equal = MoneyBag.create(new Money(12, "CHF"), new Money(7, "USD")); assertEquals(fMB1.hashCode(), equal.hashCode()); } @Test public void testMoneyEquals() { assertTrue(!f12CHF.equals(null)); Money equalMoney = new Money(12, "CHF"); assertEquals(f12CHF, f12CHF); assertEquals(f12CHF, equalMoney); assertEquals(f12CHF.hashCode(), equalMoney.hashCode()); assertTrue(!f12CHF.equals(f14CHF)); } @Test public void zeroMoniesAreEqualRegardlessOfCurrency() { Money zeroDollars = new Money(0, "USD"); Money zeroFrancs = new Money(0, "CHF"); assertEquals(zeroDollars, zeroFrancs); assertEquals(zeroDollars.hashCode(), zeroFrancs.hashCode()); } @Test public void testMoneyHash() { assertTrue(!f12CHF.equals(null)); Money equal = new Money(12, "CHF"); assertEquals(f12CHF.hashCode(), equal.hashCode()); } @Test public void testSimplify() { IMoney money = MoneyBag.create(new Money(26, "CHF"), new Money(28, "CHF")); assertEquals(new Money(54, "CHF"), money); } @Test public void testNormalize2() { // {[12 CHF][7 USD]} - [12 CHF] == [7 USD] Money expected = new Money(7, "USD"); assertEquals(expected, fMB1.subtract(f12CHF)); } @Test public void testNormalize3() { // {[12 CHF][7 USD]} - {[12 CHF][3 USD]} == [4 USD] IMoney ms1 = MoneyBag.create(new Money(12, "CHF"), new Money(3, "USD")); Money expected = new Money(4, "USD"); assertEquals(expected, fMB1.subtract(ms1)); } @Test public void testNormalize4() { // [12 CHF] - {[12 CHF][3 USD]} == [-3 USD] IMoney ms1 = MoneyBag.create(new Money(12, "CHF"), new Money(3, "USD")); Money expected = new Money(-3, "USD"); assertEquals(expected, f12CHF.subtract(ms1)); } @Test public void testPrint() { assertEquals("[12 CHF]", f12CHF.toString()); } @Test public void testSimpleAdd() { // [12 CHF] + [14 CHF] == [26 CHF] Money expected = new Money(26, "CHF"); assertEquals(expected, f12CHF.add(f14CHF)); } @Test public void testSimpleBagAdd() { // [14 CHF] + {[12 CHF][7 USD]} == {[26 CHF][7 USD]} IMoney expected = MoneyBag.create(new Money(26, "CHF"), new Money(7, "USD")); assertEquals(expected, f14CHF.add(fMB1)); } @Test public void testSimpleMultiply() { // [14 CHF] *2 == [28 CHF] Money expected = new Money(28, "CHF"); assertEquals(expected, f14CHF.multiply(2)); } @Test public void testSimpleNegate() { // [14 CHF] negate == [-14 CHF] Money expected = new Money(-14, "CHF"); assertEquals(expected, f14CHF.negate()); } @Test public void testSimpleSubtract() { // [14 CHF] - [12 CHF] == [2 CHF] Money expected = new Money(2, "CHF"); assertEquals(expected, f14CHF.subtract(f12CHF)); } }junit4-4.11/src/test/java/org/junit/samples/ListTest.java0000644000175000017500000000421312050524441022672 0ustar ebourgebourgpackage org.junit.samples; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import junit.framework.JUnit4TestAdapter; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; /** * A sample test case, testing {@link java.util.Vector}. */ public class ListTest { protected List fEmpty; protected List fFull; protected static List fgHeavy; public static void main(String... args) { junit.textui.TestRunner.run(suite()); } @BeforeClass public static void setUpOnce() { fgHeavy = new ArrayList(); for (int i = 0; i < 1000; i++) { fgHeavy.add(i); } } @Before public void setUp() { fEmpty = new ArrayList(); fFull = new ArrayList(); fFull.add(1); fFull.add(2); fFull.add(3); } public static junit.framework.Test suite() { return new JUnit4TestAdapter(ListTest.class); } @Ignore("not today") @Test public void capacity() { int size = fFull.size(); for (int i = 0; i < 100; i++) { fFull.add(i); } assertTrue(fFull.size() == 100 + size); } @Test public void testCopy() { List copy = new ArrayList(fFull.size()); copy.addAll(fFull); assertTrue(copy.size() == fFull.size()); assertTrue(copy.contains(1)); } @Test public void contains() { assertTrue(fFull.contains(1)); assertTrue(!fEmpty.contains(1)); } @Test(expected = IndexOutOfBoundsException.class) public void elementAt() { int i = fFull.get(0); assertTrue(i == 1); fFull.get(fFull.size()); // Should throw IndexOutOfBoundsException } @Test public void removeAll() { fFull.removeAll(fFull); fEmpty.removeAll(fEmpty); assertTrue(fFull.isEmpty()); assertTrue(fEmpty.isEmpty()); } @Test public void removeElement() { fFull.remove(new Integer(3)); assertTrue(!fFull.contains(3)); } }junit4-4.11/src/test/java/org/junit/samples/SimpleTest.java0000644000175000017500000000162512050524441023214 0ustar ebourgebourgpackage org.junit.samples; import static org.junit.Assert.assertEquals; import junit.framework.JUnit4TestAdapter; import org.junit.Before; import org.junit.Test; /** * Some simple tests. */ public class SimpleTest { protected int fValue1; protected int fValue2; @Before public void setUp() { fValue1 = 2; fValue2 = 3; } public static junit.framework.Test suite() { return new JUnit4TestAdapter(SimpleTest.class); } public int unused; @Test public void divideByZero() { int zero = 0; int result = 8 / zero; unused = result; // avoid warning for not using result } @Test public void testEquals() { assertEquals(12, 12); assertEquals(12L, 12L); assertEquals(new Long(12), new Long(12)); assertEquals("Size", 12, 13); assertEquals("Capacity", 12.0, 11.99, 0.0); } }junit4-4.11/src/test/java/org/junit/internal/0000755000175000017500000000000012050524441020424 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/internal/matchers/0000755000175000017500000000000012050524441022232 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/internal/matchers/StacktracePrintingMatcherTest.java0000644000175000017500000000253712050524441031047 0ustar ebourgebourgpackage org.junit.internal.matchers; import static org.hamcrest.CoreMatchers.any; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.internal.matchers.StacktracePrintingMatcher.isException; import static org.junit.internal.matchers.StacktracePrintingMatcher.isThrowable; import org.junit.Test; public class StacktracePrintingMatcherTest { @Test public void succeedsWhenInnerMatcherSucceeds() throws Exception { assertTrue(isThrowable(any(Throwable.class)).matches(new Exception())); } @Test public void failsWhenInnerMatcherFails() throws Exception { assertFalse(isException(notNullValue(Exception.class)).matches(null)); } @Test public void assertThatIncludesStacktrace() { Exception actual = new IllegalArgumentException("my message"); Exception expected = new NullPointerException(); try { assertThat(actual, isThrowable(equalTo(expected))); } catch (AssertionError e) { assertThat(e.getMessage(), containsString("Stacktrace was: java.lang.IllegalArgumentException: my message")); } } } junit4-4.11/src/test/java/org/junit/internal/MethodSorterTest.java0000644000175000017500000000716512050524441024557 0ustar ebourgebourgpackage org.junit.internal; import static org.junit.Assert.assertEquals; import java.lang.reflect.Method; import java.util.Arrays; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; public class MethodSorterTest { private static final String ALPHA = "java.lang.Object alpha(int,double,java.lang.Thread)"; private static final String BETA = "void beta(int[][])"; private static final String GAMMA_VOID = "int gamma()"; private static final String GAMMA_BOOLEAN = "void gamma(boolean)"; private static final String DELTA = "void delta()"; private static final String EPSILON = "void epsilon()"; static class Dummy { Object alpha(int i, double d, Thread t) { return null; } void beta(int[][] x) { } int gamma() { return 0; } void gamma(boolean b) { } void delta() { } void epsilon() { } } static class Super { void testOne() { } } static class Sub extends Super { void testTwo() { } } private String toString(Class clazz, Method[] methods) { return Arrays.toString(methods).replace(clazz.getName() + '.', ""); } private String declaredMethods(Class clazz) { return toString(clazz, MethodSorter.getDeclaredMethods(clazz)); } @Test public void getMethodsNullSorter() throws Exception { String[] expected = new String[]{EPSILON, BETA, ALPHA, DELTA, GAMMA_VOID, GAMMA_BOOLEAN}; assertEquals(Arrays.asList(expected).toString(), declaredMethods(Dummy.class)); assertEquals("[void testOne()]", declaredMethods(Super.class)); assertEquals("[void testTwo()]", declaredMethods(Sub.class)); } @FixMethodOrder(MethodSorters.DEFAULT) static class DummySortWithDefault { Object alpha(int i, double d, Thread t) { return null; } void beta(int[][] x) { } int gamma() { return 0; } void gamma(boolean b) { } void delta() { } void epsilon() { } } @Test public void testDefaultSorter() { String[] expected = new String[]{EPSILON, BETA, ALPHA, DELTA, GAMMA_VOID, GAMMA_BOOLEAN}; assertEquals(Arrays.asList(expected).toString(), declaredMethods(DummySortWithDefault.class)); } @FixMethodOrder(MethodSorters.JVM) static class DummySortJvm { Object alpha(int i, double d, Thread t) { return null; } void beta(int[][] x) { } int gamma() { return 0; } void gamma(boolean b) { } void delta() { } void epsilon() { } } @Test public void testSortWithJvm() { Class clazz = DummySortJvm.class; String actual = toString(clazz, clazz.getDeclaredMethods()); assertEquals(actual, declaredMethods(clazz)); } @FixMethodOrder(MethodSorters.NAME_ASCENDING) static class DummySortWithNameAsc { Object alpha(int i, double d, Thread t) { return null; } void beta(int[][] x) { } int gamma() { return 0; } void gamma(boolean b) { } void delta() { } void epsilon() { } } @Test public void testNameAsc() { String[] expected = new String[]{ALPHA, BETA, DELTA, EPSILON, GAMMA_VOID, GAMMA_BOOLEAN}; assertEquals(Arrays.asList(expected).toString(), declaredMethods(DummySortWithNameAsc.class)); } } junit4-4.11/src/test/java/org/junit/runner/0000755000175000017500000000000012050524441020121 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/runner/notification/0000755000175000017500000000000012050524441022607 5ustar ebourgebourgjunit4-4.11/src/test/java/org/junit/runner/notification/RunNotifierTest.java0000644000175000017500000000306112050524441026556 0ustar ebourgebourgpackage org.junit.runner.notification; import static org.junit.Assert.assertNotNull; import org.junit.Test; import org.junit.runner.Result; public class RunNotifierTest { @Test public void notifiesSecondListenerIfFirstThrowsException() { FailureListener failureListener = new FailureListener(); RunNotifier notifier = new RunNotifier(); notifier.addListener(new CorruptListener()); notifier.addListener(failureListener); notifier.fireTestFailure(new Failure(null, null)); assertNotNull("The FailureListener registered no failure.", failureListener.failure); } @Test public void hasNoProblemsWithFailingListeners() { // see issues 209 and 395 RunNotifier notifier = new RunNotifier(); notifier.addListener(new CorruptListener()); notifier.addListener(new FailureListener()); notifier.addListener(new CorruptListener()); notifier.fireTestRunFinished(new Result()); } private static class CorruptListener extends RunListener { @Override public void testRunFinished(Result result) throws Exception { throw new RuntimeException(); } @Override public void testFailure(Failure failure) throws Exception { throw new RuntimeException(); } } private static class FailureListener extends RunListener { private Failure failure; @Override public void testFailure(Failure failure) throws Exception { this.failure = failure; } } } junit4-4.11/src/main/0000755000175000017500000000000012050524441013714 5ustar ebourgebourgjunit4-4.11/src/main/java/0000755000175000017500000000000012050524441014635 5ustar ebourgebourgjunit4-4.11/src/main/java/junit/0000755000175000017500000000000012050524441015766 5ustar ebourgebourgjunit4-4.11/src/main/java/junit/textui/0000755000175000017500000000000012050524441017310 5ustar ebourgebourgjunit4-4.11/src/main/java/junit/textui/package-info.java0000644000175000017500000000013212050524441022473 0ustar ebourgebourg/** * Provides JUnit v3.x command line based tool to run tests. */ package junit.textui;junit4-4.11/src/main/java/junit/textui/ResultPrinter.java0000644000175000017500000000774112050524441023006 0ustar ebourgebourgpackage junit.textui; import java.io.PrintStream; import java.text.NumberFormat; import java.util.Enumeration; import junit.framework.AssertionFailedError; import junit.framework.Test; import junit.framework.TestFailure; import junit.framework.TestListener; import junit.framework.TestResult; import junit.runner.BaseTestRunner; public class ResultPrinter implements TestListener { PrintStream fWriter; int fColumn = 0; public ResultPrinter(PrintStream writer) { fWriter = writer; } /* API for use by textui.TestRunner */ synchronized void print(TestResult result, long runTime) { printHeader(runTime); printErrors(result); printFailures(result); printFooter(result); } void printWaitPrompt() { getWriter().println(); getWriter().println(" to continue"); } /* Internal methods */ protected void printHeader(long runTime) { getWriter().println(); getWriter().println("Time: " + elapsedTimeAsString(runTime)); } protected void printErrors(TestResult result) { printDefects(result.errors(), result.errorCount(), "error"); } protected void printFailures(TestResult result) { printDefects(result.failures(), result.failureCount(), "failure"); } protected void printDefects(Enumeration booBoos, int count, String type) { if (count == 0) return; if (count == 1) { getWriter().println("There was " + count + " " + type + ":"); } else { getWriter().println("There were " + count + " " + type + "s:"); } for (int i = 1; booBoos.hasMoreElements(); i++) { printDefect(booBoos.nextElement(), i); } } public void printDefect(TestFailure booBoo, int count) { // only public for testing purposes printDefectHeader(booBoo, count); printDefectTrace(booBoo); } protected void printDefectHeader(TestFailure booBoo, int count) { // I feel like making this a println, then adding a line giving the throwable a chance to print something // before we get to the stack trace. getWriter().print(count + ") " + booBoo.failedTest()); } protected void printDefectTrace(TestFailure booBoo) { getWriter().print(BaseTestRunner.getFilteredTrace(booBoo.trace())); } protected void printFooter(TestResult result) { if (result.wasSuccessful()) { getWriter().println(); getWriter().print("OK"); getWriter().println(" (" + result.runCount() + " test" + (result.runCount() == 1 ? "" : "s") + ")"); } else { getWriter().println(); getWriter().println("FAILURES!!!"); getWriter().println("Tests run: " + result.runCount() + ", Failures: " + result.failureCount() + ", Errors: " + result.errorCount()); } getWriter().println(); } /** * Returns the formatted string of the elapsed time. * Duplicated from BaseTestRunner. Fix it. */ protected String elapsedTimeAsString(long runTime) { return NumberFormat.getInstance().format((double) runTime / 1000); } public PrintStream getWriter() { return fWriter; } /** * @see junit.framework.TestListener#addError(Test, Throwable) */ public void addError(Test test, Throwable t) { getWriter().print("E"); } /** * @see junit.framework.TestListener#addFailure(Test, AssertionFailedError) */ public void addFailure(Test test, AssertionFailedError t) { getWriter().print("F"); } /** * @see junit.framework.TestListener#endTest(Test) */ public void endTest(Test test) { } /** * @see junit.framework.TestListener#startTest(Test) */ public void startTest(Test test) { getWriter().print("."); if (fColumn++ >= 40) { getWriter().println(); fColumn = 0; } } } junit4-4.11/src/main/java/junit/textui/TestRunner.java0000644000175000017500000001337212050524441022272 0ustar ebourgebourgpackage junit.textui; import java.io.PrintStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestResult; import junit.framework.TestSuite; import junit.runner.BaseTestRunner; import junit.runner.Version; /** * A command line based tool to run tests. *
     * java junit.textui.TestRunner [-wait] TestCaseClass
     * 
    * *

    TestRunner expects the name of a TestCase class as argument. * If this class defines a static suite method it * will be invoked and the returned test is run. Otherwise all * the methods starting with "test" having no arguments are run.

    * *

    When the wait command line argument is given TestRunner * waits until the users types RETURN.

    * *

    TestRunner prints a trace as the tests are executed followed by a * summary at the end.

    */ public class TestRunner extends BaseTestRunner { private ResultPrinter fPrinter; public static final int SUCCESS_EXIT = 0; public static final int FAILURE_EXIT = 1; public static final int EXCEPTION_EXIT = 2; /** * Constructs a TestRunner. */ public TestRunner() { this(System.out); } /** * Constructs a TestRunner using the given stream for all the output */ public TestRunner(PrintStream writer) { this(new ResultPrinter(writer)); } /** * Constructs a TestRunner using the given ResultPrinter all the output */ public TestRunner(ResultPrinter printer) { fPrinter = printer; } /** * Runs a suite extracted from a TestCase subclass. */ static public void run(Class testClass) { run(new TestSuite(testClass)); } /** * Runs a single test and collects its results. * This method can be used to start a test run * from your program. *
         * public static void main (String[] args) {
         *    test.textui.TestRunner.run(suite());
         * }
         * 
    */ static public TestResult run(Test test) { TestRunner runner = new TestRunner(); return runner.doRun(test); } /** * Runs a single test and waits until the user * types RETURN. */ static public void runAndWait(Test suite) { TestRunner aTestRunner = new TestRunner(); aTestRunner.doRun(suite, true); } @Override public void testFailed(int status, Test test, Throwable t) { } @Override public void testStarted(String testName) { } @Override public void testEnded(String testName) { } /** * Creates the TestResult to be used for the test run. */ protected TestResult createTestResult() { return new TestResult(); } public TestResult doRun(Test test) { return doRun(test, false); } public TestResult doRun(Test suite, boolean wait) { TestResult result = createTestResult(); result.addListener(fPrinter); long startTime = System.currentTimeMillis(); suite.run(result); long endTime = System.currentTimeMillis(); long runTime = endTime - startTime; fPrinter.print(result, runTime); pause(wait); return result; } protected void pause(boolean wait) { if (!wait) return; fPrinter.printWaitPrompt(); try { System.in.read(); } catch (Exception e) { } } public static void main(String args[]) { TestRunner aTestRunner = new TestRunner(); try { TestResult r = aTestRunner.start(args); if (!r.wasSuccessful()) { System.exit(FAILURE_EXIT); } System.exit(SUCCESS_EXIT); } catch (Exception e) { System.err.println(e.getMessage()); System.exit(EXCEPTION_EXIT); } } /** * Starts a test run. Analyzes the command line arguments and runs the given * test suite. */ public TestResult start(String args[]) throws Exception { String testCase = ""; String method = ""; boolean wait = false; for (int i = 0; i < args.length; i++) { if (args[i].equals("-wait")) { wait = true; } else if (args[i].equals("-c")) { testCase = extractClassName(args[++i]); } else if (args[i].equals("-m")) { String arg = args[++i]; int lastIndex = arg.lastIndexOf('.'); testCase = arg.substring(0, lastIndex); method = arg.substring(lastIndex + 1); } else if (args[i].equals("-v")) { System.err.println("JUnit " + Version.id() + " by Kent Beck and Erich Gamma"); } else { testCase = args[i]; } } if (testCase.equals("")) { throw new Exception("Usage: TestRunner [-wait] testCaseName, where name is the name of the TestCase class"); } try { if (!method.equals("")) { return runSingleMethod(testCase, method, wait); } Test suite = getTest(testCase); return doRun(suite, wait); } catch (Exception e) { throw new Exception("Could not create and run test suite: " + e); } } protected TestResult runSingleMethod(String testCase, String method, boolean wait) throws Exception { Class testClass = loadSuiteClass(testCase).asSubclass(TestCase.class); Test test = TestSuite.createTest(testClass, method); return doRun(test, wait); } @Override protected void runFailed(String message) { System.err.println(message); System.exit(FAILURE_EXIT); } public void setPrinter(ResultPrinter printer) { fPrinter = printer; } }junit4-4.11/src/main/java/junit/extensions/0000755000175000017500000000000012050524441020165 5ustar ebourgebourgjunit4-4.11/src/main/java/junit/extensions/TestDecorator.java0000644000175000017500000000160712050524441023616 0ustar ebourgebourgpackage junit.extensions; import junit.framework.Assert; import junit.framework.Test; import junit.framework.TestResult; /** * A Decorator for Tests. Use TestDecorator as the base class for defining new * test decorators. Test decorator subclasses can be introduced to add behaviour * before or after a test is run. */ public class TestDecorator extends Assert implements Test { protected Test fTest; public TestDecorator(Test test) { fTest = test; } /** * The basic run behaviour. */ public void basicRun(TestResult result) { fTest.run(result); } public int countTestCases() { return fTest.countTestCases(); } public void run(TestResult result) { basicRun(result); } @Override public String toString() { return fTest.toString(); } public Test getTest() { return fTest; } }junit4-4.11/src/main/java/junit/extensions/package-info.java0000644000175000017500000000012412050524441023351 0ustar ebourgebourg/** * Provides extended functionality for JUnit v3.x. */ package junit.extensions;junit4-4.11/src/main/java/junit/extensions/ActiveTestSuite.java0000644000175000017500000000336712050524441024126 0ustar ebourgebourgpackage junit.extensions; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestResult; import junit.framework.TestSuite; /** * A TestSuite for active Tests. It runs each * test in a separate thread and waits until all * threads have terminated. * -- Aarhus Radisson Scandinavian Center 11th floor */ public class ActiveTestSuite extends TestSuite { private volatile int fActiveTestDeathCount; public ActiveTestSuite() { } public ActiveTestSuite(Class theClass) { super(theClass); } public ActiveTestSuite(String name) { super(name); } public ActiveTestSuite(Class theClass, String name) { super(theClass, name); } @Override public void run(TestResult result) { fActiveTestDeathCount = 0; super.run(result); waitUntilFinished(); } @Override public void runTest(final Test test, final TestResult result) { Thread t = new Thread() { @Override public void run() { try { // inlined due to limitation in VA/Java //ActiveTestSuite.super.runTest(test, result); test.run(result); } finally { ActiveTestSuite.this.runFinished(); } } }; t.start(); } synchronized void waitUntilFinished() { while (fActiveTestDeathCount < testCount()) { try { wait(); } catch (InterruptedException e) { return; // ignore } } } synchronized public void runFinished() { fActiveTestDeathCount++; notifyAll(); } }junit4-4.11/src/main/java/junit/extensions/TestSetup.java0000644000175000017500000000204112050524441022765 0ustar ebourgebourgpackage junit.extensions; import junit.framework.Protectable; import junit.framework.Test; import junit.framework.TestResult; /** * A Decorator to set up and tear down additional fixture state. Subclass * TestSetup and insert it into your tests when you want to set up additional * state once before the tests are run. */ public class TestSetup extends TestDecorator { public TestSetup(Test test) { super(test); } @Override public void run(final TestResult result) { Protectable p = new Protectable() { public void protect() throws Exception { setUp(); basicRun(result); tearDown(); } }; result.runProtected(this, p); } /** * Sets up the fixture. Override to set up additional fixture state. */ protected void setUp() throws Exception { } /** * Tears down the fixture. Override to tear down the additional fixture * state. */ protected void tearDown() throws Exception { } }junit4-4.11/src/main/java/junit/extensions/RepeatedTest.java0000644000175000017500000000156712050524441023432 0ustar ebourgebourgpackage junit.extensions; import junit.framework.Test; import junit.framework.TestResult; /** * A Decorator that runs a test repeatedly. */ public class RepeatedTest extends TestDecorator { private int fTimesRepeat; public RepeatedTest(Test test, int repeat) { super(test); if (repeat < 0) { throw new IllegalArgumentException("Repetition count must be >= 0"); } fTimesRepeat = repeat; } @Override public int countTestCases() { return super.countTestCases() * fTimesRepeat; } @Override public void run(TestResult result) { for (int i = 0; i < fTimesRepeat; i++) { if (result.shouldStop()) { break; } super.run(result); } } @Override public String toString() { return super.toString() + "(repeated)"; } }junit4-4.11/src/main/java/junit/framework/0000755000175000017500000000000012050524441017763 5ustar ebourgebourgjunit4-4.11/src/main/java/junit/framework/ComparisonFailure.java0000644000175000017500000000263012050524441024251 0ustar ebourgebourgpackage junit.framework; /** * Thrown when an assert equals for Strings failed. * * Inspired by a patch from Alex Chaffee mailto:alex@purpletech.com */ public class ComparisonFailure extends AssertionFailedError { private static final int MAX_CONTEXT_LENGTH = 20; private static final long serialVersionUID = 1L; private String fExpected; private String fActual; /** * Constructs a comparison failure. * * @param message the identifying message or null * @param expected the expected string value * @param actual the actual string value */ public ComparisonFailure(String message, String expected, String actual) { super(message); fExpected = expected; fActual = actual; } /** * Returns "..." in place of common prefix and "..." in * place of common suffix between expected and actual. * * @see Throwable#getMessage() */ @Override public String getMessage() { return new ComparisonCompactor(MAX_CONTEXT_LENGTH, fExpected, fActual).compact(super.getMessage()); } /** * Gets the actual string value * * @return the actual string value */ public String getActual() { return fActual; } /** * Gets the expected string value * * @return the expected string value */ public String getExpected() { return fExpected; } }junit4-4.11/src/main/java/junit/framework/package-info.java0000644000175000017500000000010512050524441023146 0ustar ebourgebourg/** * Provides JUnit v3.x core classes. */ package junit.framework;junit4-4.11/src/main/java/junit/framework/Test.java0000644000175000017500000000061712050524441021551 0ustar ebourgebourgpackage junit.framework; /** * A Test can be run and collect its results. * * @see TestResult */ public interface Test { /** * Counts the number of test cases that will be run by this test. */ public abstract int countTestCases(); /** * Runs a test and collects its result in a TestResult instance. */ public abstract void run(TestResult result); }junit4-4.11/src/main/java/junit/framework/TestFailure.java0000644000175000017500000000304512050524441023057 0ustar ebourgebourgpackage junit.framework; import java.io.PrintWriter; import java.io.StringWriter; /** * A TestFailure collects a failed test together with * the caught exception. * * @see TestResult */ public class TestFailure extends Object { protected Test fFailedTest; protected Throwable fThrownException; /** * Constructs a TestFailure with the given test and exception. */ public TestFailure(Test failedTest, Throwable thrownException) { fFailedTest = failedTest; fThrownException = thrownException; } /** * Gets the failed test. */ public Test failedTest() { return fFailedTest; } /** * Gets the thrown exception. */ public Throwable thrownException() { return fThrownException; } /** * Returns a short description of the failure. */ @Override public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(fFailedTest + ": " + fThrownException.getMessage()); return buffer.toString(); } public String trace() { StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); thrownException().printStackTrace(writer); StringBuffer buffer = stringWriter.getBuffer(); return buffer.toString(); } public String exceptionMessage() { return thrownException().getMessage(); } public boolean isFailure() { return thrownException() instanceof AssertionFailedError; } }junit4-4.11/src/main/java/junit/framework/ComparisonCompactor.java0000644000175000017500000000511412050524441024611 0ustar ebourgebourgpackage junit.framework; public class ComparisonCompactor { private static final String ELLIPSIS = "..."; private static final String DELTA_END = "]"; private static final String DELTA_START = "["; private int fContextLength; private String fExpected; private String fActual; private int fPrefix; private int fSuffix; public ComparisonCompactor(int contextLength, String expected, String actual) { fContextLength = contextLength; fExpected = expected; fActual = actual; } public String compact(String message) { if (fExpected == null || fActual == null || areStringsEqual()) { return Assert.format(message, fExpected, fActual); } findCommonPrefix(); findCommonSuffix(); String expected = compactString(fExpected); String actual = compactString(fActual); return Assert.format(message, expected, actual); } private String compactString(String source) { String result = DELTA_START + source.substring(fPrefix, source.length() - fSuffix + 1) + DELTA_END; if (fPrefix > 0) { result = computeCommonPrefix() + result; } if (fSuffix > 0) { result = result + computeCommonSuffix(); } return result; } private void findCommonPrefix() { fPrefix = 0; int end = Math.min(fExpected.length(), fActual.length()); for (; fPrefix < end; fPrefix++) { if (fExpected.charAt(fPrefix) != fActual.charAt(fPrefix)) { break; } } } private void findCommonSuffix() { int expectedSuffix = fExpected.length() - 1; int actualSuffix = fActual.length() - 1; for (; actualSuffix >= fPrefix && expectedSuffix >= fPrefix; actualSuffix--, expectedSuffix--) { if (fExpected.charAt(expectedSuffix) != fActual.charAt(actualSuffix)) { break; } } fSuffix = fExpected.length() - expectedSuffix; } private String computeCommonPrefix() { return (fPrefix > fContextLength ? ELLIPSIS : "") + fExpected.substring(Math.max(0, fPrefix - fContextLength), fPrefix); } private String computeCommonSuffix() { int end = Math.min(fExpected.length() - fSuffix + 1 + fContextLength, fExpected.length()); return fExpected.substring(fExpected.length() - fSuffix + 1, end) + (fExpected.length() - fSuffix + 1 < fExpected.length() - fContextLength ? ELLIPSIS : ""); } private boolean areStringsEqual() { return fExpected.equals(fActual); } } junit4-4.11/src/main/java/junit/framework/TestResult.java0000644000175000017500000001115212050524441022744 0ustar ebourgebourgpackage junit.framework; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.List; /** * A TestResult collects the results of executing * a test case. It is an instance of the Collecting Parameter pattern. * The test framework distinguishes between failures and errors. * A failure is anticipated and checked for with assertions. Errors are * unanticipated problems like an {@link ArrayIndexOutOfBoundsException}. * * @see Test */ public class TestResult extends Object { protected List fFailures; protected List fErrors; protected List fListeners; protected int fRunTests; private boolean fStop; public TestResult() { fFailures = new ArrayList(); fErrors = new ArrayList(); fListeners = new ArrayList(); fRunTests = 0; fStop = false; } /** * Adds an error to the list of errors. The passed in exception * caused the error. */ public synchronized void addError(Test test, Throwable t) { fErrors.add(new TestFailure(test, t)); for (TestListener each : cloneListeners()) { each.addError(test, t); } } /** * Adds a failure to the list of failures. The passed in exception * caused the failure. */ public synchronized void addFailure(Test test, AssertionFailedError t) { fFailures.add(new TestFailure(test, t)); for (TestListener each : cloneListeners()) { each.addFailure(test, t); } } /** * Registers a TestListener */ public synchronized void addListener(TestListener listener) { fListeners.add(listener); } /** * Unregisters a TestListener */ public synchronized void removeListener(TestListener listener) { fListeners.remove(listener); } /** * Returns a copy of the listeners. */ private synchronized List cloneListeners() { List result = new ArrayList(); result.addAll(fListeners); return result; } /** * Informs the result that a test was completed. */ public void endTest(Test test) { for (TestListener each : cloneListeners()) { each.endTest(test); } } /** * Gets the number of detected errors. */ public synchronized int errorCount() { return fErrors.size(); } /** * Returns an Enumeration for the errors */ public synchronized Enumeration errors() { return Collections.enumeration(fErrors); } /** * Gets the number of detected failures. */ public synchronized int failureCount() { return fFailures.size(); } /** * Returns an Enumeration for the failures */ public synchronized Enumeration failures() { return Collections.enumeration(fFailures); } /** * Runs a TestCase. */ protected void run(final TestCase test) { startTest(test); Protectable p = new Protectable() { public void protect() throws Throwable { test.runBare(); } }; runProtected(test, p); endTest(test); } /** * Gets the number of run tests. */ public synchronized int runCount() { return fRunTests; } /** * Runs a TestCase. */ public void runProtected(final Test test, Protectable p) { try { p.protect(); } catch (AssertionFailedError e) { addFailure(test, e); } catch (ThreadDeath e) { // don't catch ThreadDeath by accident throw e; } catch (Throwable e) { addError(test, e); } } /** * Checks whether the test run should stop */ public synchronized boolean shouldStop() { return fStop; } /** * Informs the result that a test will be started. */ public void startTest(Test test) { final int count = test.countTestCases(); synchronized (this) { fRunTests += count; } for (TestListener each : cloneListeners()) { each.startTest(test); } } /** * Marks that the test run should stop. */ public synchronized void stop() { fStop = true; } /** * Returns whether the entire test was successful or not. */ public synchronized boolean wasSuccessful() { return failureCount() == 0 && errorCount() == 0; } }junit4-4.11/src/main/java/junit/framework/AssertionFailedError.java0000644000175000017500000000066312050524441024721 0ustar ebourgebourgpackage junit.framework; /** * Thrown when an assertion failed. */ public class AssertionFailedError extends AssertionError { private static final long serialVersionUID = 1L; public AssertionFailedError() { } public AssertionFailedError(String message) { super(defaultString(message)); } private static String defaultString(String message) { return message == null ? "" : message; } }junit4-4.11/src/main/java/junit/framework/Protectable.java0000644000175000017500000000041512050524441023072 0ustar ebourgebourgpackage junit.framework; /** * A Protectable can be run and can throw a Throwable. * * @see TestResult */ public interface Protectable { /** * Run the the following method protected. */ public abstract void protect() throws Throwable; }junit4-4.11/src/main/java/junit/framework/TestCase.java0000644000175000017500000004054712050524441022353 0ustar ebourgebourgpackage junit.framework; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; /** * A test case defines the fixture to run multiple tests. To define a test case
    *
      *
    1. implement a subclass of TestCase
    2. *
    3. define instance variables that store the state of the fixture
    4. *
    5. initialize the fixture state by overriding {@link #setUp()}
    6. *
    7. clean-up after a test by overriding {@link #tearDown()}.
    8. *
    * Each test runs in its own fixture so there * can be no side effects among test runs. * Here is an example: *
     * public class MathTest extends TestCase {
     *    protected double fValue1;
     *    protected double fValue2;
     *
     *    protected void setUp() {
     *       fValue1= 2.0;
     *       fValue2= 3.0;
     *    }
     * }
     * 
    * * For each test implement a method which interacts * with the fixture. Verify the expected results with assertions specified * by calling {@link junit.framework.Assert#assertTrue(String, boolean)} with a boolean. *
     *    public void testAdd() {
     *       double result= fValue1 + fValue2;
     *       assertTrue(result == 5.0);
     *    }
     * 
    * * Once the methods are defined you can run them. The framework supports * both a static type safe and more dynamic way to run a test. * In the static way you override the runTest method and define the method to * be invoked. A convenient way to do so is with an anonymous inner class. *
     * TestCase test= new MathTest("add") {
     *    public void runTest() {
     *       testAdd();
     *    }
     * };
     * test.run();
     * 
    * The dynamic way uses reflection to implement {@link #runTest()}. It dynamically finds * and invokes a method. * In this case the name of the test case has to correspond to the test method * to be run. *
     * TestCase test= new MathTest("testAdd");
     * test.run();
     * 
    * * The tests to be run can be collected into a TestSuite. JUnit provides * different test runners which can run a test suite and collect the results. * A test runner either expects a static method suite as the entry * point to get a test to run or it will extract the suite automatically. *
     * public static Test suite() {
     *    suite.addTest(new MathTest("testAdd"));
     *    suite.addTest(new MathTest("testDivideByZero"));
     *    return suite;
     * }
     * 
    * * @see TestResult * @see TestSuite */ public abstract class TestCase extends Assert implements Test { /** * the name of the test case */ private String fName; /** * No-arg constructor to enable serialization. This method * is not intended to be used by mere mortals without calling setName(). */ public TestCase() { fName = null; } /** * Constructs a test case with the given name. */ public TestCase(String name) { fName = name; } /** * Counts the number of test cases executed by run(TestResult result). */ public int countTestCases() { return 1; } /** * Creates a default TestResult object * * @see TestResult */ protected TestResult createResult() { return new TestResult(); } /** * A convenience method to run this test, collecting the results with a * default TestResult object. * * @see TestResult */ public TestResult run() { TestResult result = createResult(); run(result); return result; } /** * Runs the test case and collects the results in TestResult. */ public void run(TestResult result) { result.run(this); } /** * Runs the bare test sequence. * * @throws Throwable if any exception is thrown */ public void runBare() throws Throwable { Throwable exception = null; setUp(); try { runTest(); } catch (Throwable running) { exception = running; } finally { try { tearDown(); } catch (Throwable tearingDown) { if (exception == null) exception = tearingDown; } } if (exception != null) throw exception; } /** * Override to run the test and assert its state. * * @throws Throwable if any exception is thrown */ protected void runTest() throws Throwable { assertNotNull("TestCase.fName cannot be null", fName); // Some VMs crash when calling getMethod(null,null); Method runMethod = null; try { // use getMethod to get all public inherited // methods. getDeclaredMethods returns all // methods of this class but excludes the // inherited ones. runMethod = getClass().getMethod(fName, (Class[]) null); } catch (NoSuchMethodException e) { fail("Method \"" + fName + "\" not found"); } if (!Modifier.isPublic(runMethod.getModifiers())) { fail("Method \"" + fName + "\" should be public"); } try { runMethod.invoke(this); } catch (InvocationTargetException e) { e.fillInStackTrace(); throw e.getTargetException(); } catch (IllegalAccessException e) { e.fillInStackTrace(); throw e; } } /** * Asserts that a condition is true. If it isn't it throws * an AssertionFailedError with the given message. */ @SuppressWarnings("deprecation") public static void assertTrue(String message, boolean condition) { Assert.assertTrue(message, condition); } /** * Asserts that a condition is true. If it isn't it throws * an AssertionFailedError. */ @SuppressWarnings("deprecation") public static void assertTrue(boolean condition) { Assert.assertTrue(condition); } /** * Asserts that a condition is false. If it isn't it throws * an AssertionFailedError with the given message. */ @SuppressWarnings("deprecation") public static void assertFalse(String message, boolean condition) { Assert.assertFalse(message, condition); } /** * Asserts that a condition is false. If it isn't it throws * an AssertionFailedError. */ @SuppressWarnings("deprecation") public static void assertFalse(boolean condition) { Assert.assertFalse(condition); } /** * Fails a test with the given message. */ @SuppressWarnings("deprecation") public static void fail(String message) { Assert.fail(message); } /** * Fails a test with no message. */ @SuppressWarnings("deprecation") public static void fail() { Assert.fail(); } /** * Asserts that two objects are equal. If they are not * an AssertionFailedError is thrown with the given message. */ @SuppressWarnings("deprecation") public static void assertEquals(String message, Object expected, Object actual) { Assert.assertEquals(message, expected, actual); } /** * Asserts that two objects are equal. If they are not * an AssertionFailedError is thrown. */ @SuppressWarnings("deprecation") public static void assertEquals(Object expected, Object actual) { Assert.assertEquals(expected, actual); } /** * Asserts that two Strings are equal. */ @SuppressWarnings("deprecation") public static void assertEquals(String message, String expected, String actual) { Assert.assertEquals(message, expected, actual); } /** * Asserts that two Strings are equal. */ @SuppressWarnings("deprecation") public static void assertEquals(String expected, String actual) { Assert.assertEquals(expected, actual); } /** * Asserts that two doubles are equal concerning a delta. If they are not * an AssertionFailedError is thrown with the given message. If the expected * value is infinity then the delta value is ignored. */ @SuppressWarnings("deprecation") public static void assertEquals(String message, double expected, double actual, double delta) { Assert.assertEquals(message, expected, actual, delta); } /** * Asserts that two doubles are equal concerning a delta. If the expected * value is infinity then the delta value is ignored. */ @SuppressWarnings("deprecation") public static void assertEquals(double expected, double actual, double delta) { Assert.assertEquals(expected, actual, delta); } /** * Asserts that two floats are equal concerning a positive delta. If they * are not an AssertionFailedError is thrown with the given message. If the * expected value is infinity then the delta value is ignored. */ @SuppressWarnings("deprecation") public static void assertEquals(String message, float expected, float actual, float delta) { Assert.assertEquals(message, expected, actual, delta); } /** * Asserts that two floats are equal concerning a delta. If the expected * value is infinity then the delta value is ignored. */ @SuppressWarnings("deprecation") public static void assertEquals(float expected, float actual, float delta) { Assert.assertEquals(expected, actual, delta); } /** * Asserts that two longs are equal. If they are not * an AssertionFailedError is thrown with the given message. */ @SuppressWarnings("deprecation") public static void assertEquals(String message, long expected, long actual) { Assert.assertEquals(message, expected, actual); } /** * Asserts that two longs are equal. */ @SuppressWarnings("deprecation") public static void assertEquals(long expected, long actual) { Assert.assertEquals(expected, actual); } /** * Asserts that two booleans are equal. If they are not * an AssertionFailedError is thrown with the given message. */ @SuppressWarnings("deprecation") public static void assertEquals(String message, boolean expected, boolean actual) { Assert.assertEquals(message, expected, actual); } /** * Asserts that two booleans are equal. */ @SuppressWarnings("deprecation") public static void assertEquals(boolean expected, boolean actual) { Assert.assertEquals(expected, actual); } /** * Asserts that two bytes are equal. If they are not * an AssertionFailedError is thrown with the given message. */ @SuppressWarnings("deprecation") public static void assertEquals(String message, byte expected, byte actual) { Assert.assertEquals(message, expected, actual); } /** * Asserts that two bytes are equal. */ @SuppressWarnings("deprecation") public static void assertEquals(byte expected, byte actual) { Assert.assertEquals(expected, actual); } /** * Asserts that two chars are equal. If they are not * an AssertionFailedError is thrown with the given message. */ @SuppressWarnings("deprecation") public static void assertEquals(String message, char expected, char actual) { Assert.assertEquals(message, expected, actual); } /** * Asserts that two chars are equal. */ @SuppressWarnings("deprecation") public static void assertEquals(char expected, char actual) { Assert.assertEquals(expected, actual); } /** * Asserts that two shorts are equal. If they are not * an AssertionFailedError is thrown with the given message. */ @SuppressWarnings("deprecation") public static void assertEquals(String message, short expected, short actual) { Assert.assertEquals(message, expected, actual); } /** * Asserts that two shorts are equal. */ @SuppressWarnings("deprecation") public static void assertEquals(short expected, short actual) { Assert.assertEquals(expected, actual); } /** * Asserts that two ints are equal. If they are not * an AssertionFailedError is thrown with the given message. */ @SuppressWarnings("deprecation") public static void assertEquals(String message, int expected, int actual) { Assert.assertEquals(message, expected, actual); } /** * Asserts that two ints are equal. */ @SuppressWarnings("deprecation") public static void assertEquals(int expected, int actual) { Assert.assertEquals(expected, actual); } /** * Asserts that an object isn't null. */ @SuppressWarnings("deprecation") public static void assertNotNull(Object object) { Assert.assertNotNull(object); } /** * Asserts that an object isn't null. If it is * an AssertionFailedError is thrown with the given message. */ @SuppressWarnings("deprecation") public static void assertNotNull(String message, Object object) { Assert.assertNotNull(message, object); } /** * Asserts that an object is null. If it isn't an {@link AssertionError} is * thrown. * Message contains: Expected: but was: object * * @param object Object to check or null */ @SuppressWarnings("deprecation") public static void assertNull(Object object) { Assert.assertNull(object); } /** * Asserts that an object is null. If it is not * an AssertionFailedError is thrown with the given message. */ @SuppressWarnings("deprecation") public static void assertNull(String message, Object object) { Assert.assertNull(message, object); } /** * Asserts that two objects refer to the same object. If they are not * an AssertionFailedError is thrown with the given message. */ @SuppressWarnings("deprecation") public static void assertSame(String message, Object expected, Object actual) { Assert.assertSame(message, expected, actual); } /** * Asserts that two objects refer to the same object. If they are not * the same an AssertionFailedError is thrown. */ @SuppressWarnings("deprecation") public static void assertSame(Object expected, Object actual) { Assert.assertSame(expected, actual); } /** * Asserts that two objects do not refer to the same object. If they do * refer to the same object an AssertionFailedError is thrown with the * given message. */ @SuppressWarnings("deprecation") public static void assertNotSame(String message, Object expected, Object actual) { Assert.assertNotSame(message, expected, actual); } /** * Asserts that two objects do not refer to the same object. If they do * refer to the same object an AssertionFailedError is thrown. */ @SuppressWarnings("deprecation") public static void assertNotSame(Object expected, Object actual) { Assert.assertNotSame(expected, actual); } @SuppressWarnings("deprecation") public static void failSame(String message) { Assert.failSame(message); } @SuppressWarnings("deprecation") public static void failNotSame(String message, Object expected, Object actual) { Assert.failNotSame(message, expected, actual); } @SuppressWarnings("deprecation") public static void failNotEquals(String message, Object expected, Object actual) { Assert.failNotEquals(message, expected, actual); } @SuppressWarnings("deprecation") public static String format(String message, Object expected, Object actual) { return Assert.format(message, expected, actual); } /** * Sets up the fixture, for example, open a network connection. * This method is called before a test is executed. */ protected void setUp() throws Exception { } /** * Tears down the fixture, for example, close a network connection. * This method is called after a test is executed. */ protected void tearDown() throws Exception { } /** * Returns a string representation of the test case */ @Override public String toString() { return getName() + "(" + getClass().getName() + ")"; } /** * Gets the name of a TestCase * * @return the name of the TestCase */ public String getName() { return fName; } /** * Sets the name of a TestCase * * @param name the name to set */ public void setName(String name) { fName = name; } } junit4-4.11/src/main/java/junit/framework/TestListener.java0000644000175000017500000000070212050524441023252 0ustar ebourgebourgpackage junit.framework; /** * A Listener for test progress */ public interface TestListener { /** * An error occurred. */ public void addError(Test test, Throwable t); /** * A failure occurred. */ public void addFailure(Test test, AssertionFailedError t); /** * A test ended. */ public void endTest(Test test); /** * A test started. */ public void startTest(Test test); }junit4-4.11/src/main/java/junit/framework/TestSuite.java0000644000175000017500000002222412050524441022561 0ustar ebourgebourgpackage junit.framework; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Vector; import org.junit.internal.MethodSorter; /** *

    A TestSuite is a Composite of Tests. * It runs a collection of test cases. Here is an example using * the dynamic test definition. *

     * TestSuite suite= new TestSuite();
     * suite.addTest(new MathTest("testAdd"));
     * suite.addTest(new MathTest("testDivideByZero"));
     * 
    *

    * *

    Alternatively, a TestSuite can extract the tests to be run automatically. * To do so you pass the class of your TestCase class to the * TestSuite constructor. *

     * TestSuite suite= new TestSuite(MathTest.class);
     * 
    *

    * *

    This constructor creates a suite with all the methods * starting with "test" that take no arguments.

    * *

    A final option is to do the same for a large array of test classes. *

     * Class[] testClasses = { MathTest.class, AnotherTest.class }
     * TestSuite suite= new TestSuite(testClasses);
     * 
    *

    * * @see Test */ public class TestSuite implements Test { /** * ...as the moon sets over the early morning Merlin, Oregon * mountains, our intrepid adventurers type... */ static public Test createTest(Class theClass, String name) { Constructor constructor; try { constructor = getTestConstructor(theClass); } catch (NoSuchMethodException e) { return warning("Class " + theClass.getName() + " has no public constructor TestCase(String name) or TestCase()"); } Object test; try { if (constructor.getParameterTypes().length == 0) { test = constructor.newInstance(new Object[0]); if (test instanceof TestCase) { ((TestCase) test).setName(name); } } else { test = constructor.newInstance(new Object[]{name}); } } catch (InstantiationException e) { return (warning("Cannot instantiate test case: " + name + " (" + exceptionToString(e) + ")")); } catch (InvocationTargetException e) { return (warning("Exception in constructor: " + name + " (" + exceptionToString(e.getTargetException()) + ")")); } catch (IllegalAccessException e) { return (warning("Cannot access test case: " + name + " (" + exceptionToString(e) + ")")); } return (Test) test; } /** * Gets a constructor which takes a single String as * its argument or a no arg constructor. */ public static Constructor getTestConstructor(Class theClass) throws NoSuchMethodException { try { return theClass.getConstructor(String.class); } catch (NoSuchMethodException e) { // fall through } return theClass.getConstructor(new Class[0]); } /** * Returns a test which will fail and log a warning message. */ public static Test warning(final String message) { return new TestCase("warning") { @Override protected void runTest() { fail(message); } }; } /** * Converts the stack trace into a string */ private static String exceptionToString(Throwable t) { StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); t.printStackTrace(writer); return stringWriter.toString(); } private String fName; private Vector fTests = new Vector(10); // Cannot convert this to List because it is used directly by some test runners /** * Constructs an empty TestSuite. */ public TestSuite() { } /** * Constructs a TestSuite from the given class. Adds all the methods * starting with "test" as test cases to the suite. * Parts of this method were written at 2337 meters in the Hueffihuette, * Kanton Uri */ public TestSuite(final Class theClass) { addTestsFromTestCase(theClass); } private void addTestsFromTestCase(final Class theClass) { fName = theClass.getName(); try { getTestConstructor(theClass); // Avoid generating multiple error messages } catch (NoSuchMethodException e) { addTest(warning("Class " + theClass.getName() + " has no public constructor TestCase(String name) or TestCase()")); return; } if (!Modifier.isPublic(theClass.getModifiers())) { addTest(warning("Class " + theClass.getName() + " is not public")); return; } Class superClass = theClass; List names = new ArrayList(); while (Test.class.isAssignableFrom(superClass)) { for (Method each : MethodSorter.getDeclaredMethods(superClass)) { addTestMethod(each, names, theClass); } superClass = superClass.getSuperclass(); } if (fTests.size() == 0) { addTest(warning("No tests found in " + theClass.getName())); } } /** * Constructs a TestSuite from the given class with the given name. * * @see TestSuite#TestSuite(Class) */ public TestSuite(Class theClass, String name) { this(theClass); setName(name); } /** * Constructs an empty TestSuite. */ public TestSuite(String name) { setName(name); } /** * Constructs a TestSuite from the given array of classes. * * @param classes {@link TestCase}s */ public TestSuite(Class... classes) { for (Class each : classes) { addTest(testCaseForClass(each)); } } private Test testCaseForClass(Class each) { if (TestCase.class.isAssignableFrom(each)) { return new TestSuite(each.asSubclass(TestCase.class)); } else { return warning(each.getCanonicalName() + " does not extend TestCase"); } } /** * Constructs a TestSuite from the given array of classes with the given name. * * @see TestSuite#TestSuite(Class[]) */ public TestSuite(Class[] classes, String name) { this(classes); setName(name); } /** * Adds a test to the suite. */ public void addTest(Test test) { fTests.add(test); } /** * Adds the tests from the given class to the suite */ public void addTestSuite(Class testClass) { addTest(new TestSuite(testClass)); } /** * Counts the number of test cases that will be run by this test. */ public int countTestCases() { int count = 0; for (Test each : fTests) { count += each.countTestCases(); } return count; } /** * Returns the name of the suite. Not all * test suites have a name and this method * can return null. */ public String getName() { return fName; } /** * Runs the tests and collects their result in a TestResult. */ public void run(TestResult result) { for (Test each : fTests) { if (result.shouldStop()) { break; } runTest(each, result); } } public void runTest(Test test, TestResult result) { test.run(result); } /** * Sets the name of the suite. * * @param name the name to set */ public void setName(String name) { fName = name; } /** * Returns the test at the given index */ public Test testAt(int index) { return fTests.get(index); } /** * Returns the number of tests in this suite */ public int testCount() { return fTests.size(); } /** * Returns the tests as an enumeration */ public Enumeration tests() { return fTests.elements(); } /** */ @Override public String toString() { if (getName() != null) { return getName(); } return super.toString(); } private void addTestMethod(Method m, List names, Class theClass) { String name = m.getName(); if (names.contains(name)) { return; } if (!isPublicTestMethod(m)) { if (isTestMethod(m)) { addTest(warning("Test method isn't public: " + m.getName() + "(" + theClass.getCanonicalName() + ")")); } return; } names.add(name); addTest(createTest(theClass, name)); } private boolean isPublicTestMethod(Method m) { return isTestMethod(m) && Modifier.isPublic(m.getModifiers()); } private boolean isTestMethod(Method m) { return m.getParameterTypes().length == 0 && m.getName().startsWith("test") && m.getReturnType().equals(Void.TYPE); } }junit4-4.11/src/main/java/junit/framework/JUnit4TestAdapter.java0000644000175000017500000000465112050524441024112 0ustar ebourgebourgpackage junit.framework; import java.util.List; import org.junit.Ignore; import org.junit.runner.Describable; import org.junit.runner.Description; import org.junit.runner.Request; import org.junit.runner.Runner; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.Filterable; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runner.manipulation.Sortable; import org.junit.runner.manipulation.Sorter; public class JUnit4TestAdapter implements Test, Filterable, Sortable, Describable { private final Class fNewTestClass; private final Runner fRunner; private final JUnit4TestAdapterCache fCache; public JUnit4TestAdapter(Class newTestClass) { this(newTestClass, JUnit4TestAdapterCache.getDefault()); } public JUnit4TestAdapter(final Class newTestClass, JUnit4TestAdapterCache cache) { fCache = cache; fNewTestClass = newTestClass; fRunner = Request.classWithoutSuiteMethod(newTestClass).getRunner(); } public int countTestCases() { return fRunner.testCount(); } public void run(TestResult result) { fRunner.run(fCache.getNotifier(result, this)); } // reflective interface for Eclipse public List getTests() { return fCache.asTestList(getDescription()); } // reflective interface for Eclipse public Class getTestClass() { return fNewTestClass; } public Description getDescription() { Description description = fRunner.getDescription(); return removeIgnored(description); } private Description removeIgnored(Description description) { if (isIgnored(description)) { return Description.EMPTY; } Description result = description.childlessCopy(); for (Description each : description.getChildren()) { Description child = removeIgnored(each); if (!child.isEmpty()) { result.addChild(child); } } return result; } private boolean isIgnored(Description description) { return description.getAnnotation(Ignore.class) != null; } @Override public String toString() { return fNewTestClass.getName(); } public void filter(Filter filter) throws NoTestsRemainException { filter.apply(fRunner); } public void sort(Sorter sorter) { sorter.apply(fRunner); } }junit4-4.11/src/main/java/junit/framework/Assert.java0000644000175000017500000002502012050524441022066 0ustar ebourgebourgpackage junit.framework; /** * A set of assert methods. Messages are only displayed when an assert fails. * * @deprecated Please use {@link org.junit.Assert} instead. */ @Deprecated public class Assert { /** * Protect constructor since it is a static only class */ protected Assert() { } /** * Asserts that a condition is true. If it isn't it throws * an AssertionFailedError with the given message. */ static public void assertTrue(String message, boolean condition) { if (!condition) { fail(message); } } /** * Asserts that a condition is true. If it isn't it throws * an AssertionFailedError. */ static public void assertTrue(boolean condition) { assertTrue(null, condition); } /** * Asserts that a condition is false. If it isn't it throws * an AssertionFailedError with the given message. */ static public void assertFalse(String message, boolean condition) { assertTrue(message, !condition); } /** * Asserts that a condition is false. If it isn't it throws * an AssertionFailedError. */ static public void assertFalse(boolean condition) { assertFalse(null, condition); } /** * Fails a test with the given message. */ static public void fail(String message) { if (message == null) { throw new AssertionFailedError(); } throw new AssertionFailedError(message); } /** * Fails a test with no message. */ static public void fail() { fail(null); } /** * Asserts that two objects are equal. If they are not * an AssertionFailedError is thrown with the given message. */ static public void assertEquals(String message, Object expected, Object actual) { if (expected == null && actual == null) { return; } if (expected != null && expected.equals(actual)) { return; } failNotEquals(message, expected, actual); } /** * Asserts that two objects are equal. If they are not * an AssertionFailedError is thrown. */ static public void assertEquals(Object expected, Object actual) { assertEquals(null, expected, actual); } /** * Asserts that two Strings are equal. */ static public void assertEquals(String message, String expected, String actual) { if (expected == null && actual == null) { return; } if (expected != null && expected.equals(actual)) { return; } String cleanMessage = message == null ? "" : message; throw new ComparisonFailure(cleanMessage, expected, actual); } /** * Asserts that two Strings are equal. */ static public void assertEquals(String expected, String actual) { assertEquals(null, expected, actual); } /** * Asserts that two doubles are equal concerning a delta. If they are not * an AssertionFailedError is thrown with the given message. If the expected * value is infinity then the delta value is ignored. */ static public void assertEquals(String message, double expected, double actual, double delta) { if (Double.compare(expected, actual) == 0) { return; } if (!(Math.abs(expected - actual) <= delta)) { failNotEquals(message, new Double(expected), new Double(actual)); } } /** * Asserts that two doubles are equal concerning a delta. If the expected * value is infinity then the delta value is ignored. */ static public void assertEquals(double expected, double actual, double delta) { assertEquals(null, expected, actual, delta); } /** * Asserts that two floats are equal concerning a positive delta. If they * are not an AssertionFailedError is thrown with the given message. If the * expected value is infinity then the delta value is ignored. */ static public void assertEquals(String message, float expected, float actual, float delta) { if (Float.compare(expected, actual) == 0) { return; } if (!(Math.abs(expected - actual) <= delta)) { failNotEquals(message, new Float(expected), new Float(actual)); } } /** * Asserts that two floats are equal concerning a delta. If the expected * value is infinity then the delta value is ignored. */ static public void assertEquals(float expected, float actual, float delta) { assertEquals(null, expected, actual, delta); } /** * Asserts that two longs are equal. If they are not * an AssertionFailedError is thrown with the given message. */ static public void assertEquals(String message, long expected, long actual) { assertEquals(message, new Long(expected), new Long(actual)); } /** * Asserts that two longs are equal. */ static public void assertEquals(long expected, long actual) { assertEquals(null, expected, actual); } /** * Asserts that two booleans are equal. If they are not * an AssertionFailedError is thrown with the given message. */ static public void assertEquals(String message, boolean expected, boolean actual) { assertEquals(message, Boolean.valueOf(expected), Boolean.valueOf(actual)); } /** * Asserts that two booleans are equal. */ static public void assertEquals(boolean expected, boolean actual) { assertEquals(null, expected, actual); } /** * Asserts that two bytes are equal. If they are not * an AssertionFailedError is thrown with the given message. */ static public void assertEquals(String message, byte expected, byte actual) { assertEquals(message, new Byte(expected), new Byte(actual)); } /** * Asserts that two bytes are equal. */ static public void assertEquals(byte expected, byte actual) { assertEquals(null, expected, actual); } /** * Asserts that two chars are equal. If they are not * an AssertionFailedError is thrown with the given message. */ static public void assertEquals(String message, char expected, char actual) { assertEquals(message, new Character(expected), new Character(actual)); } /** * Asserts that two chars are equal. */ static public void assertEquals(char expected, char actual) { assertEquals(null, expected, actual); } /** * Asserts that two shorts are equal. If they are not * an AssertionFailedError is thrown with the given message. */ static public void assertEquals(String message, short expected, short actual) { assertEquals(message, new Short(expected), new Short(actual)); } /** * Asserts that two shorts are equal. */ static public void assertEquals(short expected, short actual) { assertEquals(null, expected, actual); } /** * Asserts that two ints are equal. If they are not * an AssertionFailedError is thrown with the given message. */ static public void assertEquals(String message, int expected, int actual) { assertEquals(message, new Integer(expected), new Integer(actual)); } /** * Asserts that two ints are equal. */ static public void assertEquals(int expected, int actual) { assertEquals(null, expected, actual); } /** * Asserts that an object isn't null. */ static public void assertNotNull(Object object) { assertNotNull(null, object); } /** * Asserts that an object isn't null. If it is * an AssertionFailedError is thrown with the given message. */ static public void assertNotNull(String message, Object object) { assertTrue(message, object != null); } /** * Asserts that an object is null. If it isn't an {@link AssertionError} is * thrown. * Message contains: Expected: but was: object * * @param object Object to check or null */ static public void assertNull(Object object) { if (object != null) { assertNull("Expected: but was: " + object.toString(), object); } } /** * Asserts that an object is null. If it is not * an AssertionFailedError is thrown with the given message. */ static public void assertNull(String message, Object object) { assertTrue(message, object == null); } /** * Asserts that two objects refer to the same object. If they are not * an AssertionFailedError is thrown with the given message. */ static public void assertSame(String message, Object expected, Object actual) { if (expected == actual) { return; } failNotSame(message, expected, actual); } /** * Asserts that two objects refer to the same object. If they are not * the same an AssertionFailedError is thrown. */ static public void assertSame(Object expected, Object actual) { assertSame(null, expected, actual); } /** * Asserts that two objects do not refer to the same object. If they do * refer to the same object an AssertionFailedError is thrown with the * given message. */ static public void assertNotSame(String message, Object expected, Object actual) { if (expected == actual) { failSame(message); } } /** * Asserts that two objects do not refer to the same object. If they do * refer to the same object an AssertionFailedError is thrown. */ static public void assertNotSame(Object expected, Object actual) { assertNotSame(null, expected, actual); } static public void failSame(String message) { String formatted = (message != null) ? message + " " : ""; fail(formatted + "expected not same"); } static public void failNotSame(String message, Object expected, Object actual) { String formatted = (message != null) ? message + " " : ""; fail(formatted + "expected same:<" + expected + "> was not:<" + actual + ">"); } static public void failNotEquals(String message, Object expected, Object actual) { fail(format(message, expected, actual)); } public static String format(String message, Object expected, Object actual) { String formatted = ""; if (message != null && message.length() > 0) { formatted = message + " "; } return formatted + "expected:<" + expected + "> but was:<" + actual + ">"; } } junit4-4.11/src/main/java/junit/framework/JUnit4TestCaseFacade.java0000644000175000017500000000127312050524441024466 0ustar ebourgebourgpackage junit.framework; import org.junit.runner.Describable; import org.junit.runner.Description; public class JUnit4TestCaseFacade implements Test, Describable { private final Description fDescription; JUnit4TestCaseFacade(Description description) { fDescription = description; } @Override public String toString() { return getDescription().toString(); } public int countTestCases() { return 1; } public void run(TestResult result) { throw new RuntimeException( "This test stub created only for informational purposes."); } public Description getDescription() { return fDescription; } }junit4-4.11/src/main/java/junit/framework/JUnit4TestAdapterCache.java0000644000175000017500000000473412050524441025040 0ustar ebourgebourgpackage junit.framework; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import org.junit.runner.Description; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; import org.junit.runner.notification.RunNotifier; public class JUnit4TestAdapterCache extends HashMap { private static final long serialVersionUID = 1L; private static final JUnit4TestAdapterCache fInstance = new JUnit4TestAdapterCache(); public static JUnit4TestAdapterCache getDefault() { return fInstance; } public Test asTest(Description description) { if (description.isSuite()) { return createTest(description); } else { if (!containsKey(description)) { put(description, createTest(description)); } return get(description); } } Test createTest(Description description) { if (description.isTest()) { return new JUnit4TestCaseFacade(description); } else { TestSuite suite = new TestSuite(description.getDisplayName()); for (Description child : description.getChildren()) { suite.addTest(asTest(child)); } return suite; } } public RunNotifier getNotifier(final TestResult result, final JUnit4TestAdapter adapter) { RunNotifier notifier = new RunNotifier(); notifier.addListener(new RunListener() { @Override public void testFailure(Failure failure) throws Exception { result.addError(asTest(failure.getDescription()), failure.getException()); } @Override public void testFinished(Description description) throws Exception { result.endTest(asTest(description)); } @Override public void testStarted(Description description) throws Exception { result.startTest(asTest(description)); } }); return notifier; } public List asTestList(Description description) { if (description.isTest()) { return Arrays.asList(asTest(description)); } else { List returnThis = new ArrayList(); for (Description child : description.getChildren()) { returnThis.add(asTest(child)); } return returnThis; } } }junit4-4.11/src/main/java/junit/runner/0000755000175000017500000000000012050524441017277 5ustar ebourgebourgjunit4-4.11/src/main/java/junit/runner/package-info.java0000644000175000017500000000010212050524441022457 0ustar ebourgebourg/** * Provides JUnit v3.x test runners. */ package junit.runner;junit4-4.11/src/main/java/junit/runner/logo.gif0000644000175000017500000000170412050524441020730 0ustar ebourgebourgGIF89a& ! ,&@HD#B(1 b(ѠE C,Ñ(KrHE/3tQI(mn̙Seŏ?<9TC'4h͖JD0hTX{N%!ή jҊ)wz'Χ3R-JnۥbE.W{;գU~D;q@;junit4-4.11/src/main/java/junit/runner/BaseTestRunner.java0000644000175000017500000002327712050524441023061 0ustar ebourgebourgpackage junit.runner; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.text.NumberFormat; import java.util.Properties; import junit.framework.AssertionFailedError; import junit.framework.Test; import junit.framework.TestListener; import junit.framework.TestSuite; /** * Base class for all test runners. * This class was born live on stage in Sardinia during XP2000. */ public abstract class BaseTestRunner implements TestListener { public static final String SUITE_METHODNAME = "suite"; private static Properties fPreferences; static int fgMaxMessageLength = 500; static boolean fgFilterStack = true; boolean fLoading = true; /* * Implementation of TestListener */ public synchronized void startTest(Test test) { testStarted(test.toString()); } protected static void setPreferences(Properties preferences) { fPreferences = preferences; } protected static Properties getPreferences() { if (fPreferences == null) { fPreferences = new Properties(); fPreferences.put("loading", "true"); fPreferences.put("filterstack", "true"); readPreferences(); } return fPreferences; } public static void savePreferences() throws IOException { FileOutputStream fos = new FileOutputStream(getPreferencesFile()); try { getPreferences().store(fos, ""); } finally { fos.close(); } } public static void setPreference(String key, String value) { getPreferences().put(key, value); } public synchronized void endTest(Test test) { testEnded(test.toString()); } public synchronized void addError(final Test test, final Throwable t) { testFailed(TestRunListener.STATUS_ERROR, test, t); } public synchronized void addFailure(final Test test, final AssertionFailedError t) { testFailed(TestRunListener.STATUS_FAILURE, test, t); } // TestRunListener implementation public abstract void testStarted(String testName); public abstract void testEnded(String testName); public abstract void testFailed(int status, Test test, Throwable t); /** * Returns the Test corresponding to the given suite. This is * a template method, subclasses override runFailed(), clearStatus(). */ public Test getTest(String suiteClassName) { if (suiteClassName.length() <= 0) { clearStatus(); return null; } Class testClass = null; try { testClass = loadSuiteClass(suiteClassName); } catch (ClassNotFoundException e) { String clazz = e.getMessage(); if (clazz == null) { clazz = suiteClassName; } runFailed("Class not found \"" + clazz + "\""); return null; } catch (Exception e) { runFailed("Error: " + e.toString()); return null; } Method suiteMethod = null; try { suiteMethod = testClass.getMethod(SUITE_METHODNAME, new Class[0]); } catch (Exception e) { // try to extract a test suite automatically clearStatus(); return new TestSuite(testClass); } if (!Modifier.isStatic(suiteMethod.getModifiers())) { runFailed("Suite() method must be static"); return null; } Test test = null; try { test = (Test) suiteMethod.invoke(null, (Object[]) new Class[0]); // static method if (test == null) { return test; } } catch (InvocationTargetException e) { runFailed("Failed to invoke suite():" + e.getTargetException().toString()); return null; } catch (IllegalAccessException e) { runFailed("Failed to invoke suite():" + e.toString()); return null; } clearStatus(); return test; } /** * Returns the formatted string of the elapsed time. */ public String elapsedTimeAsString(long runTime) { return NumberFormat.getInstance().format((double) runTime / 1000); } /** * Processes the command line arguments and * returns the name of the suite class to run or null */ protected String processArguments(String[] args) { String suiteName = null; for (int i = 0; i < args.length; i++) { if (args[i].equals("-noloading")) { setLoading(false); } else if (args[i].equals("-nofilterstack")) { fgFilterStack = false; } else if (args[i].equals("-c")) { if (args.length > i + 1) { suiteName = extractClassName(args[i + 1]); } else { System.out.println("Missing Test class name"); } i++; } else { suiteName = args[i]; } } return suiteName; } /** * Sets the loading behaviour of the test runner */ public void setLoading(boolean enable) { fLoading = enable; } /** * Extract the class name from a String in VA/Java style */ public String extractClassName(String className) { if (className.startsWith("Default package for")) { return className.substring(className.lastIndexOf(".") + 1); } return className; } /** * Truncates a String to the maximum length. */ public static String truncate(String s) { if (fgMaxMessageLength != -1 && s.length() > fgMaxMessageLength) { s = s.substring(0, fgMaxMessageLength) + "..."; } return s; } /** * Override to define how to handle a failed loading of * a test suite. */ protected abstract void runFailed(String message); /** * Returns the loaded Class for a suite name. */ protected Class loadSuiteClass(String suiteClassName) throws ClassNotFoundException { return Class.forName(suiteClassName); } /** * Clears the status message. */ protected void clearStatus() { // Belongs in the GUI TestRunner class } protected boolean useReloadingTestSuiteLoader() { return getPreference("loading").equals("true") && fLoading; } private static File getPreferencesFile() { String home = System.getProperty("user.home"); return new File(home, "junit.properties"); } private static void readPreferences() { InputStream is = null; try { is = new FileInputStream(getPreferencesFile()); setPreferences(new Properties(getPreferences())); getPreferences().load(is); } catch (IOException e) { try { if (is != null) { is.close(); } } catch (IOException e1) { } } } public static String getPreference(String key) { return getPreferences().getProperty(key); } public static int getPreference(String key, int dflt) { String value = getPreference(key); int intValue = dflt; if (value == null) { return intValue; } try { intValue = Integer.parseInt(value); } catch (NumberFormatException ne) { } return intValue; } /** * Returns a filtered stack trace */ public static String getFilteredTrace(Throwable t) { StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); t.printStackTrace(writer); StringBuffer buffer = stringWriter.getBuffer(); String trace = buffer.toString(); return BaseTestRunner.getFilteredTrace(trace); } /** * Filters stack frames from internal JUnit classes */ public static String getFilteredTrace(String stack) { if (showStackRaw()) { return stack; } StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); StringReader sr = new StringReader(stack); BufferedReader br = new BufferedReader(sr); String line; try { while ((line = br.readLine()) != null) { if (!filterLine(line)) { pw.println(line); } } } catch (Exception IOException) { return stack; // return the stack unfiltered } return sw.toString(); } protected static boolean showStackRaw() { return !getPreference("filterstack").equals("true") || fgFilterStack == false; } static boolean filterLine(String line) { String[] patterns = new String[]{ "junit.framework.TestCase", "junit.framework.TestResult", "junit.framework.TestSuite", "junit.framework.Assert.", // don't filter AssertionFailure "junit.swingui.TestRunner", "junit.awtui.TestRunner", "junit.textui.TestRunner", "java.lang.reflect.Method.invoke(" }; for (int i = 0; i < patterns.length; i++) { if (line.indexOf(patterns[i]) > 0) { return true; } } return false; } static { fgMaxMessageLength = getPreference("maxmessage", fgMaxMessageLength); } } junit4-4.11/src/main/java/junit/runner/Version.java.template0000644000175000017500000000043412050524441023402 0ustar ebourgebourgpackage junit.runner; /** * This class defines the current version of JUnit */ public class Version { private Version() { // don't instantiate } public static String id() { return "@version@"; } public static void main(String[] args) { System.out.println(id()); } } junit4-4.11/src/main/java/junit/runner/Version.java0000644000175000017500000000050312050524441021565 0ustar ebourgebourgpackage junit.runner; /** * This class defines the current version of JUnit */ public class Version { private Version() { // don't instantiate } public static String id() { return "4.11-SNAPSHOT"; } public static void main(String[] args) { System.out.println(id()); } } junit4-4.11/src/main/java/junit/runner/smalllogo.gif0000644000175000017500000000156312050524441021764 0ustar ebourgebourgGIF89a,@XHA L@`Hq"C%fH‚+"P9qGUIS$ɚ _iQgD(]!ɒ+\Z3 ;junit4-4.11/src/main/java/junit/runner/TestRunListener.java0000644000175000017500000000131312050524441023252 0ustar ebourgebourgpackage junit.runner; /** * A listener interface for observing the * execution of a test run. Unlike TestListener, * this interface using only primitive objects, * making it suitable for remote test execution. */ public interface TestRunListener { /* test status constants*/ public static final int STATUS_ERROR = 1; public static final int STATUS_FAILURE = 2; public void testRunStarted(String testSuiteName, int testCount); public void testRunEnded(long elapsedTime); public void testRunStopped(long elapsedTime); public void testStarted(String testName); public void testEnded(String testName); public void testFailed(int status, String testName, String trace); } junit4-4.11/src/main/java/org/0000755000175000017500000000000012050524441015424 5ustar ebourgebourgjunit4-4.11/src/main/java/org/junit/0000755000175000017500000000000012050524441016555 5ustar ebourgebourgjunit4-4.11/src/main/java/org/junit/Assume.java0000644000175000017500000001304612050524441020661 0ustar ebourgebourgpackage org.junit; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.everyItem; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import org.hamcrest.Matcher; import org.junit.internal.AssumptionViolatedException; /** * A set of methods useful for stating assumptions about the conditions in which a test is meaningful. * A failed assumption does not mean the code is broken, but that the test provides no useful information. * The default JUnit runner treats tests with failing assumptions as ignored. Custom runners may behave differently. * * For example: *
     * // only provides information if database is reachable.
     * \@Test public void calculateTotalSalary() {
     *    DBConnection dbc = Database.connect();
     *    assumeNotNull(dbc);
     *    // ...
     * }
     * 
    * These methods can be used directly: Assume.assumeTrue(...), however, they * read better if they are referenced through static import:
    *
     * import static org.junit.Assume.*;
     *    ...
     *    assumeTrue(...);
     * 
    * * @since 4.4 */ public class Assume { /** * If called with an expression evaluating to {@code false}, the test will halt and be ignored. */ public static void assumeTrue(boolean b) { assumeThat(b, is(true)); } /** * The inverse of {@link #assumeTrue(boolean)}. */ public static void assumeFalse(boolean b) { assumeTrue(!b); } /** * If called with an expression evaluating to {@code false}, the test will halt and be ignored. * * @param b If false, the method will attempt to stop the test and ignore it by * throwing {@link AssumptionViolatedException}. * @param message A message to pass to {@link AssumptionViolatedException}. */ public static void assumeTrue(String message, boolean b) { if (!b) throw new AssumptionViolatedException(message); } /** * The inverse of {@link #assumeTrue(String, boolean)}. */ public static void assumeFalse(String message, boolean b) { assumeTrue(message, !b); } /** * If called with one or more null elements in objects, the test will halt and be ignored. */ public static void assumeNotNull(Object... objects) { assumeThat(asList(objects), everyItem(notNullValue())); } /** * Call to assume that actual satisfies the condition specified by matcher. * If not, the test halts and is ignored. * Example: *
    :
         *   assumeThat(1, is(1)); // passes
         *   foo(); // will execute
         *   assumeThat(0, is(1)); // assumption failure! test halts
         *   int x = 1 / 0; // will never execute
         * 
    * * @param the static type accepted by the matcher (this can flag obvious compile-time problems such as {@code assumeThat(1, is("a"))} * @param actual the computed value being compared * @param matcher an expression, built of {@link Matcher}s, specifying allowed values * @see org.hamcrest.CoreMatchers * @see org.junit.matchers.JUnitMatchers */ public static void assumeThat(T actual, Matcher matcher) { if (!matcher.matches(actual)) { throw new AssumptionViolatedException(actual, matcher); } } /** * Call to assume that actual satisfies the condition specified by matcher. * If not, the test halts and is ignored. * Example: *
    :
         *   assumeThat(1, is(1)); // passes
         *   foo(); // will execute
         *   assumeThat(0, is(1)); // assumption failure! test halts
         *   int x = 1 / 0; // will never execute
         * 
    * * @param the static type accepted by the matcher (this can flag obvious compile-time problems such as {@code assumeThat(1, is("a"))} * @param actual the computed value being compared * @param matcher an expression, built of {@link Matcher}s, specifying allowed values * @see org.hamcrest.CoreMatchers * @see org.junit.matchers.JUnitMatchers */ public static void assumeThat(String message, T actual, Matcher matcher) { if (!matcher.matches(actual)) { throw new AssumptionViolatedException(message, actual, matcher); } } /** * Use to assume that an operation completes normally. If {@code t} is non-null, the test will halt and be ignored. * * For example: *
         * \@Test public void parseDataFile() {
         *   DataFile file;
         *   try {
         *     file = DataFile.open("sampledata.txt");
         *   } catch (IOException e) {
         *     // stop test and ignore if data can't be opened
         *     assumeNoException(e);
         *   }
         *   // ...
         * }
         * 
    * * @param t if non-null, the offending exception */ public static void assumeNoException(Throwable t) { assumeThat(t, nullValue()); } /** * Attempts to halt the test and ignore it if Throwable t is * not null. Similar to {@link #assumeNoException(Throwable)}, * but provides an additional message that can explain the details * concerning the assumption. * * @param t if non-null, the offending exception * @param message Additional message to pass to {@link AssumptionViolatedException}. * @see #assumeNoException(Throwable) */ public static void assumeNoException(String message, Throwable t) { assumeThat(message, t, nullValue()); } } junit4-4.11/src/main/java/org/junit/BeforeClass.java0000644000175000017500000000214312050524441021610 0ustar ebourgebourgpackage org.junit; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** *

    Sometimes several tests need to share computationally expensive setup * (like logging into a database). While this can compromise the independence of * tests, sometimes it is a necessary optimization. Annotating a public static void no-arg method * with @BeforeClass causes it to be run once before any of * the test methods in the class. The @BeforeClass methods of superclasses * will be run before those the current class, unless they are shadowed in the current class.

    * * For example: *
     * public class Example {
     *    @BeforeClass public static void onlyOnce() {
     *       ...
     *    }
     *    @Test public void one() {
     *       ...
     *    }
     *    @Test public void two() {
     *       ...
     *    }
     * }
     * 
    * * @see org.junit.AfterClass * @since 4.0 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface BeforeClass { } junit4-4.11/src/main/java/org/junit/ComparisonFailure.java0000644000175000017500000001203412050524441023042 0ustar ebourgebourgpackage org.junit; /** * Thrown when an {@link org.junit.Assert#assertEquals(Object, Object) assertEquals(String, String)} fails. Create and throw * a ComparisonFailure manually if you want to show users the difference between two complex * strings. * * Inspired by a patch from Alex Chaffee (alex@purpletech.com) * * @since 4.0 */ public class ComparisonFailure extends AssertionError { /** * The maximum length for fExpected and fActual. If it is exceeded, the strings should be shortened. * * @see ComparisonCompactor */ private static final int MAX_CONTEXT_LENGTH = 20; private static final long serialVersionUID = 1L; private String fExpected; private String fActual; /** * Constructs a comparison failure. * * @param message the identifying message or null * @param expected the expected string value * @param actual the actual string value */ public ComparisonFailure(String message, String expected, String actual) { super(message); fExpected = expected; fActual = actual; } /** * Returns "..." in place of common prefix and "..." in * place of common suffix between expected and actual. * * @see Throwable#getMessage() */ @Override public String getMessage() { return new ComparisonCompactor(MAX_CONTEXT_LENGTH, fExpected, fActual).compact(super.getMessage()); } /** * Returns the actual string value * * @return the actual string value */ public String getActual() { return fActual; } /** * Returns the expected string value * * @return the expected string value */ public String getExpected() { return fExpected; } private static class ComparisonCompactor { private static final String ELLIPSIS = "..."; private static final String DELTA_END = "]"; private static final String DELTA_START = "["; /** * The maximum length for expected and actual. When contextLength * is exceeded, the Strings are shortened */ private int fContextLength; private String fExpected; private String fActual; private int fPrefix; private int fSuffix; /** * @param contextLength the maximum length for expected and actual. When contextLength * is exceeded, the Strings are shortened * @param expected the expected string value * @param actual the actual string value */ public ComparisonCompactor(int contextLength, String expected, String actual) { fContextLength = contextLength; fExpected = expected; fActual = actual; } private String compact(String message) { if (fExpected == null || fActual == null || areStringsEqual()) { return Assert.format(message, fExpected, fActual); } findCommonPrefix(); findCommonSuffix(); String expected = compactString(fExpected); String actual = compactString(fActual); return Assert.format(message, expected, actual); } private String compactString(String source) { String result = DELTA_START + source.substring(fPrefix, source.length() - fSuffix + 1) + DELTA_END; if (fPrefix > 0) { result = computeCommonPrefix() + result; } if (fSuffix > 0) { result = result + computeCommonSuffix(); } return result; } private void findCommonPrefix() { fPrefix = 0; int end = Math.min(fExpected.length(), fActual.length()); for (; fPrefix < end; fPrefix++) { if (fExpected.charAt(fPrefix) != fActual.charAt(fPrefix)) { break; } } } private void findCommonSuffix() { int expectedSuffix = fExpected.length() - 1; int actualSuffix = fActual.length() - 1; for (; actualSuffix >= fPrefix && expectedSuffix >= fPrefix; actualSuffix--, expectedSuffix--) { if (fExpected.charAt(expectedSuffix) != fActual.charAt(actualSuffix)) { break; } } fSuffix = fExpected.length() - expectedSuffix; } private String computeCommonPrefix() { return (fPrefix > fContextLength ? ELLIPSIS : "") + fExpected.substring(Math.max(0, fPrefix - fContextLength), fPrefix); } private String computeCommonSuffix() { int end = Math.min(fExpected.length() - fSuffix + 1 + fContextLength, fExpected.length()); return fExpected.substring(fExpected.length() - fSuffix + 1, end) + (fExpected.length() - fSuffix + 1 < fExpected.length() - fContextLength ? ELLIPSIS : ""); } private boolean areStringsEqual() { return fExpected.equals(fActual); } } }junit4-4.11/src/main/java/org/junit/AfterClass.java0000644000175000017500000000264312050524441021454 0ustar ebourgebourgpackage org.junit; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** *

    If you allocate expensive external resources in a {@link org.junit.BeforeClass} method you need to release them * after all the tests in the class have run. Annotating a public static void method * with @AfterClass causes that method to be run after all the tests in the class have been run. All @AfterClass * methods are guaranteed to run even if a {@link org.junit.BeforeClass} method throws an * exception. The @AfterClass methods declared in superclasses will be run after those of the current * class, unless they are shadowed in the current class.

    * * Here is a simple example: *
     * public class Example {
     *    private static DatabaseConnection database;
     *    @BeforeClass public static void login() {
     *          database= ...;
     *    }
     *    @Test public void something() {
     *          ...
     *    }
     *    @Test public void somethingElse() {
     *          ...
     *    }
     *    @AfterClass public static void logout() {
     *          database.logout();
     *    }
     * }
     * 
    * * @see org.junit.BeforeClass * @see org.junit.Test * @since 4.0 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface AfterClass { } junit4-4.11/src/main/java/org/junit/package-info.java0000644000175000017500000000021712050524441021744 0ustar ebourgebourg/** * Provides JUnit core classes and annotations. * * Corresponds to junit.framework in Junit 3.x. * * @since 4.0 */ package org.junit;junit4-4.11/src/main/java/org/junit/rules/0000755000175000017500000000000012050524441017707 5ustar ebourgebourgjunit4-4.11/src/main/java/org/junit/rules/ExternalResource.java0000644000175000017500000000330312050524441024043 0ustar ebourgebourgpackage org.junit.rules; import org.junit.runner.Description; import org.junit.runners.model.Statement; /** * A base class for Rules (like TemporaryFolder) that set up an external * resource before a test (a file, socket, server, database connection, etc.), * and guarantee to tear it down afterward: * *
     * public static class UsesExternalResource {
     *  Server myServer= new Server();
     *
     *  @Rule
     *  public ExternalResource resource= new ExternalResource() {
     *      @Override
     *      protected void before() throws Throwable {
     *          myServer.connect();
     *         };
     *
     *      @Override
     *      protected void after() {
     *          myServer.disconnect();
     *         };
     *     };
     *
     *  @Test
     *  public void testFoo() {
     *      new Client().run(myServer);
     *     }
     * }
     * 
    * * @since 4.7 */ public abstract class ExternalResource implements TestRule { public Statement apply(Statement base, Description description) { return statement(base); } private Statement statement(final Statement base) { return new Statement() { @Override public void evaluate() throws Throwable { before(); try { base.evaluate(); } finally { after(); } } }; } /** * Override to set up your specific external resource. * * @throws if setup fails (which will disable {@code after} */ protected void before() throws Throwable { // do nothing } /** * Override to tear down your specific external resource. */ protected void after() { // do nothing } } junit4-4.11/src/main/java/org/junit/rules/TestWatchman.java0000644000175000017500000000456312050524441023164 0ustar ebourgebourgpackage org.junit.rules; import org.junit.internal.AssumptionViolatedException; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; /** * TestWatchman is a base class for Rules that take note of the testing * action, without modifying it. For example, this class will keep a log of each * passing and failing test: * *
     * public static class WatchmanTest {
     *  private static String watchedLog;
     *
     *  @Rule
     *  public MethodRule watchman= new TestWatchman() {
     *      @Override
     *      public void failed(Throwable e, FrameworkMethod method) {
     *          watchedLog+= method.getName() + " " + e.getClass().getSimpleName()
     *                  + "\n";
     *         }
     *
     *      @Override
     *      public void succeeded(FrameworkMethod method) {
     *          watchedLog+= method.getName() + " " + "success!\n";
     *         }
     *     };
     *
     *  @Test
     *  public void fails() {
     *      fail();
     *     }
     *
     *  @Test
     *  public void succeeds() {
     *     }
     * }
     * 
    * * @since 4.7 * @deprecated Use {@link TestWatcher} (which implements {@link TestRule}) instead. */ @Deprecated public class TestWatchman implements MethodRule { public Statement apply(final Statement base, final FrameworkMethod method, Object target) { return new Statement() { @Override public void evaluate() throws Throwable { starting(method); try { base.evaluate(); succeeded(method); } catch (AssumptionViolatedException e) { throw e; } catch (Throwable t) { failed(t, method); throw t; } finally { finished(method); } } }; } /** * Invoked when a test method succeeds */ public void succeeded(FrameworkMethod method) { } /** * Invoked when a test method fails */ public void failed(Throwable e, FrameworkMethod method) { } /** * Invoked when a test method is about to start */ public void starting(FrameworkMethod method) { } /** * Invoked when a test method finishes (whether passing or failing) */ public void finished(FrameworkMethod method) { } } junit4-4.11/src/main/java/org/junit/rules/RunRules.java0000644000175000017500000000137212050524441022334 0ustar ebourgebourgpackage org.junit.rules; import org.junit.runner.Description; import org.junit.runners.model.Statement; /** * Runs a collection of rules on a statement. * * @since 4.9 */ public class RunRules extends Statement { private final Statement statement; public RunRules(Statement base, Iterable rules, Description description) { statement = applyAll(base, rules, description); } @Override public void evaluate() throws Throwable { statement.evaluate(); } private static Statement applyAll(Statement result, Iterable rules, Description description) { for (TestRule each : rules) { result = each.apply(result, description); } return result; } } junit4-4.11/src/main/java/org/junit/rules/ExpectedExceptionMatcherBuilder.java0000644000175000017500000000224112050524441027004 0ustar ebourgebourgpackage org.junit.rules; import static org.hamcrest.CoreMatchers.allOf; import static org.junit.matchers.JUnitMatchers.isThrowable; import java.util.ArrayList; import java.util.List; import org.hamcrest.Matcher; /** * Builds special matcher used by {@link ExpectedException}. */ class ExpectedExceptionMatcherBuilder { private final List> fMatchers = new ArrayList>(); void add(Matcher matcher) { fMatchers.add(matcher); } boolean expectsThrowable() { return !fMatchers.isEmpty(); } Matcher build() { return isThrowable(allOfTheMatchers()); } private Matcher allOfTheMatchers() { if (fMatchers.size() == 1) { return cast(fMatchers.get(0)); } return allOf(castedMatchers()); } @SuppressWarnings({"unchecked", "rawtypes"}) private List> castedMatchers() { return new ArrayList>((List) fMatchers); } @SuppressWarnings("unchecked") private Matcher cast(Matcher singleMatcher) { return (Matcher) singleMatcher; } } junit4-4.11/src/main/java/org/junit/rules/Verifier.java0000644000175000017500000000235412050524441022331 0ustar ebourgebourgpackage org.junit.rules; import org.junit.runner.Description; import org.junit.runners.model.Statement; /** * Verifier is a base class for Rules like ErrorCollector, which can turn * otherwise passing test methods into failing tests if a verification check is * failed * *
     *     public static class ErrorLogVerifier() {
     *        private ErrorLog errorLog = new ErrorLog();
     *
     *        @Rule
     *        public Verifier verifier = new Verifier() {
     *           @Override public void verify() {
     *              assertTrue(errorLog.isEmpty());
     *           }
     *        }
     *
     *        @Test public void testThatMightWriteErrorLog() {
     *           // ...
     *        }
     *     }
     * 
    * * @since 4.7 */ public abstract class Verifier implements TestRule { public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { base.evaluate(); verify(); } }; } /** * Override this to add verification logic. Overrides should throw an * exception to indicate that verification failed. */ protected void verify() throws Throwable { } } junit4-4.11/src/main/java/org/junit/rules/RuleChain.java0000644000175000017500000000532012050524441022424 0ustar ebourgebourgpackage org.junit.rules; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.runner.Description; import org.junit.runners.model.Statement; /** * The RuleChain rule allows ordering of TestRules. You create a * {@code RuleChain} with {@link #outerRule(TestRule)} and subsequent calls of * {@link #around(TestRule)}: * *
     * public static class UseRuleChain {
     * 	@Rule
     * 	public RuleChain chain= RuleChain
     * 	                       .outerRule(new LoggingRule("outer rule")
     * 	                       .around(new LoggingRule("middle rule")
     * 	                       .around(new LoggingRule("inner rule");
     *
     * 	@Test
     * 	public void example() {
     * 		assertTrue(true);
     *     }
     * }
     * 
    * * writes the log * *
     * starting outer rule
     * starting middle rule
     * starting inner rule
     * finished inner rule
     * finished middle rule
     * finished outer rule
     * 
    * * @since 4.10 */ public class RuleChain implements TestRule { private static final RuleChain EMPTY_CHAIN = new RuleChain( Collections.emptyList()); private List rulesStartingWithInnerMost; /** * Returns a {@code RuleChain} without a {@link TestRule}. This method may * be the starting point of a {@code RuleChain}. * * @return a {@code RuleChain} without a {@link TestRule}. */ public static RuleChain emptyRuleChain() { return EMPTY_CHAIN; } /** * Returns a {@code RuleChain} with a single {@link TestRule}. This method * is the usual starting point of a {@code RuleChain}. * * @param outerRule the outer rule of the {@code RuleChain}. * @return a {@code RuleChain} with a single {@link TestRule}. */ public static RuleChain outerRule(TestRule outerRule) { return emptyRuleChain().around(outerRule); } private RuleChain(List rules) { this.rulesStartingWithInnerMost = rules; } /** * Create a new {@code RuleChain}, which encloses the {@code nextRule} with * the rules of the current {@code RuleChain}. * * @param enclosedRule the rule to enclose. * @return a new {@code RuleChain}. */ public RuleChain around(TestRule enclosedRule) { List rulesOfNewChain = new ArrayList(); rulesOfNewChain.add(enclosedRule); rulesOfNewChain.addAll(rulesStartingWithInnerMost); return new RuleChain(rulesOfNewChain); } /** * {@inheritDoc} */ public Statement apply(Statement base, Description description) { for (TestRule each : rulesStartingWithInnerMost) { base = each.apply(base, description); } return base; } }junit4-4.11/src/main/java/org/junit/rules/Timeout.java0000644000175000017500000000177612050524441022213 0ustar ebourgebourgpackage org.junit.rules; import org.junit.internal.runners.statements.FailOnTimeout; import org.junit.runner.Description; import org.junit.runners.model.Statement; /** * The Timeout Rule applies the same timeout to all test methods in a class: * *
     * public static class HasGlobalTimeout {
     *  public static String log;
     *
     *  @Rule
     *  public Timeout globalTimeout= new Timeout(20);
     *
     *  @Test
     *  public void testInfiniteLoop1() {
     *      log+= "ran1";
     *      for (;;) {
     *         }
     *     }
     *
     *  @Test
     *  public void testInfiniteLoop2() {
     *      log+= "ran2";
     *      for (;;) {
     *         }
     *     }
     * }
     * 
    * * @since 4.7 */ public class Timeout implements TestRule { private final int fMillis; /** * @param millis the millisecond timeout */ public Timeout(int millis) { fMillis = millis; } public Statement apply(Statement base, Description description) { return new FailOnTimeout(base, fMillis); } }junit4-4.11/src/main/java/org/junit/rules/ExpectedException.java0000644000175000017500000001426412050524441024201 0ustar ebourgebourgpackage org.junit.rules; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.junit.internal.matchers.ThrowableCauseMatcher.hasCause; import static org.junit.internal.matchers.ThrowableMessageMatcher.hasMessage; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; import org.junit.internal.AssumptionViolatedException; import org.junit.runners.model.Statement; /** * The ExpectedException rule allows in-test specification of expected exception * types and messages: * *
     * // These tests all pass.
     * public static class HasExpectedException {
     * 	@Rule
     * 	public ExpectedException thrown= ExpectedException.none();
     *
     * 	@Test
     * 	public void throwsNothing() {
     * 		// no exception expected, none thrown: passes.
     *     }
     *
     * 	@Test
     * 	public void throwsNullPointerException() {
     * 		thrown.expect(NullPointerException.class);
     * 		throw new NullPointerException();
     *     }
     *
     * 	@Test
     * 	public void throwsNullPointerExceptionWithMessage() {
     * 		thrown.expect(NullPointerException.class);
     * 		thrown.expectMessage("happened?");
     * 		thrown.expectMessage(startsWith("What"));
     * 		throw new NullPointerException("What happened?");
     *     }
     *
     * 	@Test
     * 	public void throwsIllegalArgumentExceptionWithMessageAndCause() {
     * 		NullPointerException expectedCause = new NullPointerException();
     * 		thrown.expect(IllegalArgumentException.class);
     * 		thrown.expectMessage("What");
     * 		thrown.expectCause(is(expectedCause));
     * 		throw new IllegalArgumentException("What happened?", cause);
     *     }
     * }
     * 
    * * By default ExpectedException rule doesn't handle AssertionErrors and * AssumptionViolatedExceptions, because such exceptions are used by JUnit. If * you want to handle such exceptions you have to call @link * {@link #handleAssertionErrors()} or @link * {@link #handleAssumptionViolatedExceptions()}. * *
     * // These tests all pass.
     * public static class HasExpectedException {
     * 	@Rule
     * 	public ExpectedException thrown= ExpectedException.none();
     *
     * 	@Test
     * 	public void throwExpectedAssertionError() {
     * 		thrown.handleAssertionErrors();
     * 		thrown.expect(AssertionError.class);
     * 		throw new AssertionError();
     *     }
     *
     *  @Test
     *  public void throwExpectAssumptionViolatedException() {
     *      thrown.handleAssumptionViolatedExceptions();
     *      thrown.expect(AssumptionViolatedException.class);
     *      throw new AssumptionViolatedException("");
     *     }
     * }
     * 
    * * @since 4.7 */ public class ExpectedException implements TestRule { /** * @return a Rule that expects no exception to be thrown (identical to * behavior without this Rule) */ public static ExpectedException none() { return new ExpectedException(); } private final ExpectedExceptionMatcherBuilder fMatcherBuilder = new ExpectedExceptionMatcherBuilder(); private boolean handleAssumptionViolatedExceptions = false; private boolean handleAssertionErrors = false; private ExpectedException() { } public ExpectedException handleAssertionErrors() { handleAssertionErrors = true; return this; } public ExpectedException handleAssumptionViolatedExceptions() { handleAssumptionViolatedExceptions = true; return this; } public Statement apply(Statement base, org.junit.runner.Description description) { return new ExpectedExceptionStatement(base); } /** * Adds {@code matcher} to the list of requirements for any thrown * exception. */ public void expect(Matcher matcher) { fMatcherBuilder.add(matcher); } /** * Adds to the list of requirements for any thrown exception that it should * be an instance of {@code type} */ public void expect(Class type) { expect(instanceOf(type)); } /** * Adds to the list of requirements for any thrown exception that it should * contain string {@code substring} */ public void expectMessage(String substring) { expectMessage(containsString(substring)); } /** * Adds {@code matcher} to the list of requirements for the message returned * from any thrown exception. */ public void expectMessage(Matcher matcher) { expect(hasMessage(matcher)); } /** * Adds {@code matcher} to the list of requirements for the cause of * any thrown exception. */ public void expectCause(Matcher expectedCause) { expect(hasCause(expectedCause)); } private class ExpectedExceptionStatement extends Statement { private final Statement fNext; public ExpectedExceptionStatement(Statement base) { fNext = base; } @Override public void evaluate() throws Throwable { try { fNext.evaluate(); if (fMatcherBuilder.expectsThrowable()) { failDueToMissingException(); } } catch (AssumptionViolatedException e) { optionallyHandleException(e, handleAssumptionViolatedExceptions); } catch (AssertionError e) { optionallyHandleException(e, handleAssertionErrors); } catch (Throwable e) { handleException(e); } } } private void failDueToMissingException() throws AssertionError { String expectation = StringDescription.toString(fMatcherBuilder.build()); fail("Expected test to throw " + expectation); } private void optionallyHandleException(Throwable e, boolean handleException) throws Throwable { if (handleException) { handleException(e); } else { throw e; } } private void handleException(Throwable e) throws Throwable { if (fMatcherBuilder.expectsThrowable()) { assertThat(e, fMatcherBuilder.build()); } else { throw e; } } } junit4-4.11/src/main/java/org/junit/rules/ErrorCollector.java0000644000175000017500000000514112050524441023513 0ustar ebourgebourgpackage org.junit.rules; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import org.hamcrest.Matcher; import org.junit.runners.model.MultipleFailureException; /** * The ErrorCollector rule allows execution of a test to continue after the * first problem is found (for example, to collect _all_ the incorrect rows in a * table, and report them all at once): * *
     * public static class UsesErrorCollectorTwice {
     * 	@Rule
     * 	public ErrorCollector collector= new ErrorCollector();
     *
     * @Test
     * public void example() {
     *      collector.addError(new Throwable("first thing went wrong"));
     *      collector.addError(new Throwable("second thing went wrong"));
     *      collector.checkThat(getResult(), not(containsString("ERROR!")));
     *      // all lines will run, and then a combined failure logged at the end.
     *     }
     * }
     * 
    * * @since 4.7 */ public class ErrorCollector extends Verifier { private List errors = new ArrayList(); @Override protected void verify() throws Throwable { MultipleFailureException.assertEmpty(errors); } /** * Adds a Throwable to the table. Execution continues, but the test will fail at the end. */ public void addError(Throwable error) { errors.add(error); } /** * Adds a failure to the table if {@code matcher} does not match {@code value}. * Execution continues, but the test will fail at the end if the match fails. */ public void checkThat(final T value, final Matcher matcher) { checkThat("", value, matcher); } /** * Adds a failure with the given {@code reason} * to the table if {@code matcher} does not match {@code value}. * Execution continues, but the test will fail at the end if the match fails. */ public void checkThat(final String reason, final T value, final Matcher matcher) { checkSucceeds(new Callable() { public Object call() throws Exception { assertThat(reason, value, matcher); return value; } }); } /** * Adds to the table the exception, if any, thrown from {@code callable}. * Execution continues, but the test will fail at the end if * {@code callable} threw an exception. */ public Object checkSucceeds(Callable callable) { try { return callable.call(); } catch (Throwable e) { addError(e); return null; } } }junit4-4.11/src/main/java/org/junit/rules/TestRule.java0000644000175000017500000000517312050524441022327 0ustar ebourgebourgpackage org.junit.rules; import org.junit.runner.Description; import org.junit.runners.model.Statement; /** * A TestRule is an alteration in how a test method, or set of test methods, * is run and reported. A {@link TestRule} may add additional checks that cause * a test that would otherwise fail to pass, or it may perform necessary setup or * cleanup for tests, or it may observe test execution to report it elsewhere. * {@link TestRule}s can do everything that could be done previously with * methods annotated with {@link org.junit.Before}, * {@link org.junit.After}, {@link org.junit.BeforeClass}, or * {@link org.junit.AfterClass}, but they are more powerful, and more easily * shared * between projects and classes. * * The default JUnit test runners for suites and * individual test cases recognize {@link TestRule}s introduced in two different * ways. {@link org.junit.Rule} annotates method-level * {@link TestRule}s, and {@link org.junit.ClassRule} * annotates class-level {@link TestRule}s. See Javadoc for those annotations * for more information. * * Multiple {@link TestRule}s can be applied to a test or suite execution. The * {@link Statement} that executes the method or suite is passed to each annotated * {@link org.junit.Rule} in turn, and each may return a substitute or modified * {@link Statement}, which is passed to the next {@link org.junit.Rule}, if any. For * examples of how this can be useful, see these provided TestRules, * or write your own: * *
      *
    • {@link ErrorCollector}: collect multiple errors in one test method
    • *
    • {@link ExpectedException}: make flexible assertions about thrown exceptions
    • *
    • {@link ExternalResource}: start and stop a server, for example
    • *
    • {@link TemporaryFolder}: create fresh files, and delete after test
    • *
    • {@link TestName}: remember the test name for use during the method
    • *
    • {@link TestWatcher}: add logic at events during method execution
    • *
    • {@link Timeout}: cause test to fail after a set time
    • *
    • {@link Verifier}: fail test if object state ends up incorrect
    • *
    * * @since 4.9 */ public interface TestRule { /** * Modifies the method-running {@link Statement} to implement this * test-running rule. * * @param base The {@link Statement} to be modified * @param description A {@link Description} of the test implemented in {@code base} * @return a new statement, which may be the same as {@code base}, * a wrapper around {@code base}, or a completely new Statement. */ Statement apply(Statement base, Description description); } junit4-4.11/src/main/java/org/junit/rules/TemporaryFolder.java0000644000175000017500000001006712050524441023674 0ustar ebourgebourgpackage org.junit.rules; import java.io.File; import java.io.IOException; import org.junit.Rule; /** * The TemporaryFolder Rule allows creation of files and folders that are * guaranteed to be deleted when the test method finishes (whether it passes or * fails): * *
     * public static class HasTempFolder {
     *  @Rule
     *  public TemporaryFolder folder= new TemporaryFolder();
     *
     *  @Test
     *  public void testUsingTempFolder() throws IOException {
     *      File createdFile= folder.newFile("myfile.txt");
     *      File createdFolder= folder.newFolder("subfolder");
     *      // ...
     *     }
     * }
     * 
    * * @since 4.7 */ public class TemporaryFolder extends ExternalResource { private final File parentFolder; private File folder; public TemporaryFolder() { this(null); } public TemporaryFolder(File parentFolder) { this.parentFolder = parentFolder; } @Override protected void before() throws Throwable { create(); } @Override protected void after() { delete(); } // testing purposes only /** * for testing purposes only. Do not use. */ public void create() throws IOException { folder = createTemporaryFolderIn(parentFolder); } /** * Returns a new fresh file with the given name under the temporary folder. */ public File newFile(String fileName) throws IOException { File file = new File(getRoot(), fileName); if (!file.createNewFile()) { throw new IOException( "a file with the name \'" + fileName + "\' already exists in the test folder"); } return file; } /** * Returns a new fresh file with a random name under the temporary folder. */ public File newFile() throws IOException { return File.createTempFile("junit", null, getRoot()); } /** * Returns a new fresh folder with the given name under the temporary * folder. */ public File newFolder(String folder) throws IOException { return newFolder(new String[]{folder}); } /** * Returns a new fresh folder with the given name(s) under the temporary * folder. */ public File newFolder(String... folderNames) throws IOException { File file = getRoot(); for (int i = 0; i < folderNames.length; i++) { String folderName = folderNames[i]; file = new File(file, folderName); if (!file.mkdir() && isLastElementInArray(i, folderNames)) { throw new IOException( "a folder with the name \'" + folderName + "\' already exists"); } } return file; } private boolean isLastElementInArray(int index, String[] array) { return index == array.length - 1; } /** * Returns a new fresh folder with a random name under the temporary folder. */ public File newFolder() throws IOException { return createTemporaryFolderIn(getRoot()); } private File createTemporaryFolderIn(File parentFolder) throws IOException { File createdFolder = File.createTempFile("junit", "", parentFolder); createdFolder.delete(); createdFolder.mkdir(); return createdFolder; } /** * @return the location of this temporary folder. */ public File getRoot() { if (folder == null) { throw new IllegalStateException( "the temporary folder has not yet been created"); } return folder; } /** * Delete all files and folders under the temporary folder. Usually not * called directly, since it is automatically applied by the {@link Rule} */ public void delete() { if (folder != null) { recursiveDelete(folder); } } private void recursiveDelete(File file) { File[] files = file.listFiles(); if (files != null) { for (File each : files) { recursiveDelete(each); } } file.delete(); } } junit4-4.11/src/main/java/org/junit/rules/MethodRule.java0000644000175000017500000000364112050524441022626 0ustar ebourgebourgpackage org.junit.rules; import org.junit.Rule; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; /** * A MethodRule is an alteration in how a test method is run and reported. * Multiple {@link MethodRule}s can be applied to a test method. The * {@link Statement} that executes the method is passed to each annotated * {@link Rule} in turn, and each may return a substitute or modified * {@link Statement}, which is passed to the next {@link Rule}, if any. For * examples of how this can be useful, see these provided MethodRules, * or write your own: * *
      *
    • {@link ErrorCollector}: collect multiple errors in one test method
    • *
    • {@link ExpectedException}: make flexible assertions about thrown exceptions
    • *
    • {@link ExternalResource}: start and stop a server, for example
    • *
    • {@link TemporaryFolder}: create fresh files, and delete after test
    • *
    • {@link TestName}: remember the test name for use during the method
    • *
    • {@link TestWatchman}: add logic at events during method execution
    • *
    • {@link Timeout}: cause test to fail after a set time
    • *
    • {@link Verifier}: fail test if object state ends up incorrect
    • *
    * * Note that {@link MethodRule} has been replaced by {@link TestRule}, * which has the added benefit of supporting class rules. * * @since 4.7 */ public interface MethodRule { /** * Modifies the method-running {@link Statement} to implement an additional * test-running rule. * * @param base The {@link Statement} to be modified * @param method The method to be run * @param target The object on with the method will be run. * @return a new statement, which may be the same as {@code base}, * a wrapper around {@code base}, or a completely new Statement. */ Statement apply(Statement base, FrameworkMethod method, Object target); }junit4-4.11/src/main/java/org/junit/rules/TestWatcher.java0000644000175000017500000000753312050524441023017 0ustar ebourgebourgpackage org.junit.rules; import java.util.ArrayList; import java.util.List; import org.junit.internal.AssumptionViolatedException; import org.junit.runner.Description; import org.junit.runners.model.MultipleFailureException; import org.junit.runners.model.Statement; /** * TestWatcher is a base class for Rules that take note of the testing * action, without modifying it. For example, this class will keep a log of each * passing and failing test: * *
     * public static class WatchmanTest {
     *  private static String watchedLog;
     *
     *  @Rule
     *  public TestWatcher watchman= new TestWatcher() {
     *      @Override
     *      protected void failed(Throwable e, Description description) {
     *          watchedLog+= description + "\n";
     *      }
     *
     *      @Override
     *      protected void succeeded(Description description) {
     *          watchedLog+= description + " " + "success!\n";
     *         }
     *     };
     *
     *  @Test
     *  public void fails() {
     *      fail();
     *  }
     *
     *  @Test
     *  public void succeeds() {
     *     }
     * }
     * 
    * * @since 4.9 */ public abstract class TestWatcher implements TestRule { public Statement apply(final Statement base, final Description description) { return new Statement() { @Override public void evaluate() throws Throwable { List errors = new ArrayList(); startingQuietly(description, errors); try { base.evaluate(); succeededQuietly(description, errors); } catch (AssumptionViolatedException e) { errors.add(e); skippedQuietly(e, description, errors); } catch (Throwable t) { errors.add(t); failedQuietly(t, description, errors); } finally { finishedQuietly(description, errors); } MultipleFailureException.assertEmpty(errors); } }; } private void succeededQuietly(Description description, List errors) { try { succeeded(description); } catch (Throwable t) { errors.add(t); } } private void failedQuietly(Throwable t, Description description, List errors) { try { failed(t, description); } catch (Throwable t1) { errors.add(t1); } } private void skippedQuietly(AssumptionViolatedException e, Description description, List errors) { try { skipped(e, description); } catch (Throwable t) { errors.add(t); } } private void startingQuietly(Description description, List errors) { try { starting(description); } catch (Throwable t) { errors.add(t); } } private void finishedQuietly(Description description, List errors) { try { finished(description); } catch (Throwable t) { errors.add(t); } } /** * Invoked when a test succeeds */ protected void succeeded(Description description) { } /** * Invoked when a test fails */ protected void failed(Throwable e, Description description) { } /** * Invoked when a test is skipped due to a failed assumption. */ protected void skipped(AssumptionViolatedException e, Description description) { } /** * Invoked when a test is about to start */ protected void starting(Description description) { } /** * Invoked when a test method finishes (whether passing or failing) */ protected void finished(Description description) { } } junit4-4.11/src/main/java/org/junit/rules/TestName.java0000644000175000017500000000147712050524441022303 0ustar ebourgebourgpackage org.junit.rules; import org.junit.runner.Description; /** * The TestName Rule makes the current test name available inside test methods: * *
     * public class TestNameTest {
     *  @Rule
     *  public TestName name= new TestName();
     *
     *  @Test
     *  public void testA() {
     *      assertEquals("testA", name.getMethodName());
     *     }
     *
     *  @Test
     *  public void testB() {
     *      assertEquals("testB", name.getMethodName());
     *     }
     * }
     * 
    * * @since 4.7 */ public class TestName extends TestWatcher { private String fName; @Override protected void starting(Description d) { fName = d.getMethodName(); } /** * @return the name of the currently-running test method */ public String getMethodName() { return fName; } } junit4-4.11/src/main/java/org/junit/Test.java0000644000175000017500000000452212050524441020342 0ustar ebourgebourgpackage org.junit; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** *

    The Test annotation tells JUnit that the public void method * to which it is attached can be run as a test case. To run the method, * JUnit first constructs a fresh instance of the class then invokes the * annotated method. Any exceptions thrown by the test will be reported * by JUnit as a failure. If no exceptions are thrown, the test is assumed * to have succeeded.

    * *

    A simple test looks like this: *

     * public class Example {
     *    @Test
     *    public void method() {
     *       org.junit.Assert.assertTrue( new ArrayList().isEmpty() );
     *    }
     * }
     * 
    *

    * *

    The Test annotation supports two optional parameters. * The first, expected, declares that a test method should throw * an exception. If it doesn't throw an exception or if it throws a different exception * than the one declared, the test fails. For example, the following test succeeds: *

     *    @Test(expected=IndexOutOfBoundsException.class) public void outOfBounds() {
     *       new ArrayList<Object>().get(1);
     *    }
     * 

    * *

    The second optional parameter, timeout, causes a test to fail if it takes * longer than a specified amount of clock time (measured in milliseconds). The following test fails: *

     *    @Test(timeout=100) public void infinity() {
     *       while(true);
     *    }
     * 

    * * @since 4.0 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface Test { /** * Default empty exception */ static class None extends Throwable { private static final long serialVersionUID = 1L; private None() { } } /** * Optionally specify expected, a Throwable, to cause a test method to succeed iff * an exception of the specified class is thrown by the method. */ Class expected() default None.class; /** * Optionally specify timeout in milliseconds to cause a test method to fail if it * takes longer than that number of milliseconds. */ long timeout() default 0L; } junit4-4.11/src/main/java/org/junit/ClassRule.java0000644000175000017500000000607112050524441021321 0ustar ebourgebourgpackage org.junit; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotates static fields that reference rules or methods that return them. A field must be public, * static, and a subtype of {@link org.junit.rules.TestRule}. A method must be public static, and return * a subtype of {@link org.junit.rules.TestRule}.

    * * The {@link org.junit.runners.model.Statement} passed * to the {@link org.junit.rules.TestRule} will run any {@link BeforeClass} methods, * then the entire body of the test class (all contained methods, if it is * a standard JUnit test class, or all contained classes, if it is a * {@link org.junit.runners.Suite}), and finally any {@link AfterClass} methods. * * The statement passed to the {@link org.junit.rules.TestRule} will never throw an exception, * and throwing an exception from the {@link org.junit.rules.TestRule} will result in undefined * behavior. This means that some {@link org.junit.rules.TestRule}s, such as * {@link org.junit.rules.ErrorCollector}, * {@link org.junit.rules.ExpectedException}, * and {@link org.junit.rules.Timeout}, * have undefined behavior when used as {@link ClassRule}s. * * If there are multiple * annotated {@link ClassRule}s on a class, they will be applied in an order * that depends on your JVM's implementation of the reflection API, which is * undefined, in general. However, Rules defined by fields will always be applied * before Rules defined by methods. * * For example, here is a test suite that connects to a server once before * all the test classes run, and disconnects after they are finished: * *

     * @RunWith(Suite.class)
     * @SuiteClasses({A.class, B.class, C.class})
     * public class UsesExternalResource {
     *     public static Server myServer= new Server();
     *
     *     @ClassRule
     *     public static ExternalResource resource= new ExternalResource() {
     *       @Override
     *       protected void before() throws Throwable {
     *          myServer.connect();
     *      }
     *
     *      @Override
     *      protected void after() {
     * 	        myServer.disconnect();
     *      }
     *   };
     * }
     * 
    * * and the same using a method * *
     * @RunWith(Suite.class)
     * @SuiteClasses({A.class, B.class, C.class})
     * public class UsesExternalResource {
     *     public static Server myServer= new Server();
     *
     *     @ClassRule
     *     public static ExternalResource getResource() {
     *         return new ExternalResource() {
     *             @Override
     *             protected void before() throws Throwable {
     *                 myServer.connect();
     *             }
     *
     *             @Override
     *             protected void after() {
     *                 myServer.disconnect();
     *             }
     *         };
     *     }
     * }
     * 
    * * For more information and more examples, see {@link org.junit.rules.TestRule}. * * @since 4.9 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD}) public @interface ClassRule { } junit4-4.11/src/main/java/org/junit/After.java0000644000175000017500000000241512050524441020463 0ustar ebourgebourgpackage org.junit; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** *

    If you allocate external resources in a {@link org.junit.Before} method you need to release them * after the test runs. Annotating a public void method * with @After causes that method to be run after the {@link org.junit.Test} method. All @After * methods are guaranteed to run even if a {@link org.junit.Before} or {@link org.junit.Test} method throws an * exception. The @After methods declared in superclasses will be run after those of the current * class, unless they are overridden in the current class.

    * * Here is a simple example: *
     * public class Example {
     *    File output;
     *    @Before public void createOutputFile() {
     *          output= new File(...);
     *    }
     *    @Test public void something() {
     *          ...
     *    }
     *    @After public void deleteOutputFile() {
     *          output.delete();
     *    }
     * }
     * 
    * * @see org.junit.Before * @see org.junit.Test * @since 4.0 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface After { } junit4-4.11/src/main/java/org/junit/experimental/0000755000175000017500000000000012050524441021252 5ustar ebourgebourgjunit4-4.11/src/main/java/org/junit/experimental/max/0000755000175000017500000000000012050524441022037 5ustar ebourgebourgjunit4-4.11/src/main/java/org/junit/experimental/max/MaxHistory.java0000644000175000017500000001214312050524441025012 0ustar ebourgebourgpackage org.junit.experimental.max; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import org.junit.runner.Description; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; /** * Stores a subset of the history of each test: *
      *
    • Last failure timestamp *
    • Duration of last execution *
    */ public class MaxHistory implements Serializable { private static final long serialVersionUID = 1L; /** * Loads a {@link MaxHistory} from {@code file}, or generates a new one that * will be saved to {@code file}. */ public static MaxHistory forFolder(File file) { if (file.exists()) { try { return readHistory(file); } catch (CouldNotReadCoreException e) { e.printStackTrace(); file.delete(); } } return new MaxHistory(file); } private static MaxHistory readHistory(File storedResults) throws CouldNotReadCoreException { try { FileInputStream file = new FileInputStream(storedResults); try { ObjectInputStream stream = new ObjectInputStream(file); try { return (MaxHistory) stream.readObject(); } finally { stream.close(); } } finally { file.close(); } } catch (Exception e) { throw new CouldNotReadCoreException(e); } } private final Map fDurations = new HashMap(); private final Map fFailureTimestamps = new HashMap(); private final File fHistoryStore; private MaxHistory(File storedResults) { fHistoryStore = storedResults; } private void save() throws IOException { ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream( fHistoryStore)); stream.writeObject(this); stream.close(); } Long getFailureTimestamp(Description key) { return fFailureTimestamps.get(key.toString()); } void putTestFailureTimestamp(Description key, long end) { fFailureTimestamps.put(key.toString(), end); } boolean isNewTest(Description key) { return !fDurations.containsKey(key.toString()); } Long getTestDuration(Description key) { return fDurations.get(key.toString()); } void putTestDuration(Description description, long duration) { fDurations.put(description.toString(), duration); } private final class RememberingListener extends RunListener { private long overallStart = System.currentTimeMillis(); private Map starts = new HashMap(); @Override public void testStarted(Description description) throws Exception { starts.put(description, System.nanoTime()); // Get most accurate // possible time } @Override public void testFinished(Description description) throws Exception { long end = System.nanoTime(); long start = starts.get(description); putTestDuration(description, end - start); } @Override public void testFailure(Failure failure) throws Exception { putTestFailureTimestamp(failure.getDescription(), overallStart); } @Override public void testRunFinished(Result result) throws Exception { save(); } } private class TestComparator implements Comparator { public int compare(Description o1, Description o2) { // Always prefer new tests if (isNewTest(o1)) { return -1; } if (isNewTest(o2)) { return 1; } // Then most recently failed first int result = getFailure(o2).compareTo(getFailure(o1)); return result != 0 ? result // Then shorter tests first : getTestDuration(o1).compareTo(getTestDuration(o2)); } private Long getFailure(Description key) { Long result = getFailureTimestamp(key); if (result == null) { return 0L; // 0 = "never failed (that I know about)" } return result; } } /** * @return a listener that will update this history based on the test * results reported. */ public RunListener listener() { return new RememberingListener(); } /** * @return a comparator that ranks tests based on the JUnit Max sorting * rules, as described in the {@link MaxCore} class comment. */ public Comparator testComparator() { return new TestComparator(); } } junit4-4.11/src/main/java/org/junit/experimental/max/CouldNotReadCoreException.java0000644000175000017500000000050712050524441027717 0ustar ebourgebourgpackage org.junit.experimental.max; /** * Thrown when Max cannot read the MaxCore serialization */ public class CouldNotReadCoreException extends Exception { private static final long serialVersionUID = 1L; /** * Constructs */ public CouldNotReadCoreException(Throwable e) { super(e); } } junit4-4.11/src/main/java/org/junit/experimental/max/MaxCore.java0000644000175000017500000001442112050524441024242 0ustar ebourgebourgpackage org.junit.experimental.max; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; import junit.framework.TestSuite; import org.junit.internal.requests.SortingRequest; import org.junit.internal.runners.ErrorReportingRunner; import org.junit.internal.runners.JUnit38ClassRunner; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.Request; import org.junit.runner.Result; import org.junit.runner.Runner; import org.junit.runners.Suite; import org.junit.runners.model.InitializationError; /** * A replacement for JUnitCore, which keeps track of runtime and failure history, and reorders tests * to maximize the chances that a failing test occurs early in the test run. * * The rules for sorting are: *
      *
    1. Never-run tests first, in arbitrary order *
    2. Group remaining tests by the date at which they most recently failed. *
    3. Sort groups such that the most recent failure date is first, and never-failing tests are at the end. *
    4. Within a group, run the fastest tests first. *
    */ public class MaxCore { private static final String MALFORMED_JUNIT_3_TEST_CLASS_PREFIX = "malformed JUnit 3 test class: "; /** * Create a new MaxCore from a serialized file stored at storedResults * * @deprecated use storedLocally() */ @Deprecated public static MaxCore forFolder(String folderName) { return storedLocally(new File(folderName)); } /** * Create a new MaxCore from a serialized file stored at storedResults */ public static MaxCore storedLocally(File storedResults) { return new MaxCore(storedResults); } private final MaxHistory fHistory; private MaxCore(File storedResults) { fHistory = MaxHistory.forFolder(storedResults); } /** * Run all the tests in class. * * @return a {@link Result} describing the details of the test run and the failed tests. */ public Result run(Class testClass) { return run(Request.aClass(testClass)); } /** * Run all the tests contained in request. * * @param request the request describing tests * @return a {@link Result} describing the details of the test run and the failed tests. */ public Result run(Request request) { return run(request, new JUnitCore()); } /** * Run all the tests contained in request. * * This variant should be used if {@code core} has attached listeners that this * run should notify. * * @param request the request describing tests * @param core a JUnitCore to delegate to. * @return a {@link Result} describing the details of the test run and the failed tests. */ public Result run(Request request, JUnitCore core) { core.addListener(fHistory.listener()); return core.run(sortRequest(request).getRunner()); } /** * @return a new Request, which contains all of the same tests, but in a new order. */ public Request sortRequest(Request request) { if (request instanceof SortingRequest) { // We'll pay big karma points for this return request; } List leaves = findLeaves(request); Collections.sort(leaves, fHistory.testComparator()); return constructLeafRequest(leaves); } private Request constructLeafRequest(List leaves) { final List runners = new ArrayList(); for (Description each : leaves) { runners.add(buildRunner(each)); } return new Request() { @Override public Runner getRunner() { try { return new Suite((Class) null, runners) { }; } catch (InitializationError e) { return new ErrorReportingRunner(null, e); } } }; } private Runner buildRunner(Description each) { if (each.toString().equals("TestSuite with 0 tests")) { return Suite.emptySuite(); } if (each.toString().startsWith(MALFORMED_JUNIT_3_TEST_CLASS_PREFIX)) { // This is cheating, because it runs the whole class // to get the warning for this method, but we can't do better, // because JUnit 3.8's // thrown away which method the warning is for. return new JUnit38ClassRunner(new TestSuite(getMalformedTestClass(each))); } Class type = each.getTestClass(); if (type == null) { throw new RuntimeException("Can't build a runner from description [" + each + "]"); } String methodName = each.getMethodName(); if (methodName == null) { return Request.aClass(type).getRunner(); } return Request.method(type, methodName).getRunner(); } private Class getMalformedTestClass(Description each) { try { return Class.forName(each.toString().replace(MALFORMED_JUNIT_3_TEST_CLASS_PREFIX, "")); } catch (ClassNotFoundException e) { return null; } } /** * @param request a request to run * @return a list of method-level tests to run, sorted in the order * specified in the class comment. */ public List sortedLeavesForTest(Request request) { return findLeaves(sortRequest(request)); } private List findLeaves(Request request) { List results = new ArrayList(); findLeaves(null, request.getRunner().getDescription(), results); return results; } private void findLeaves(Description parent, Description description, List results) { if (description.getChildren().isEmpty()) { if (description.toString().equals("warning(junit.framework.TestSuite$1)")) { results.add(Description.createSuiteDescription(MALFORMED_JUNIT_3_TEST_CLASS_PREFIX + parent)); } else { results.add(description); } } else { for (Description each : description.getChildren()) { findLeaves(description, each, results); } } } }junit4-4.11/src/main/java/org/junit/experimental/results/0000755000175000017500000000000012050524441022753 5ustar ebourgebourgjunit4-4.11/src/main/java/org/junit/experimental/results/PrintableResult.java0000644000175000017500000000317012050524441026736 0ustar ebourgebourgpackage org.junit.experimental.results; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.List; import org.junit.internal.TextListener; import org.junit.runner.JUnitCore; import org.junit.runner.Request; import org.junit.runner.Result; import org.junit.runner.notification.Failure; /** * A test result that prints nicely in error messages. * This is only intended to be used in JUnit self-tests. * For example: * *
     *    assertThat(testResult(HasExpectedException.class), isSuccessful());
     * 
    */ public class PrintableResult { private Result result; /** * The result of running JUnit on {@code type} */ public static PrintableResult testResult(Class type) { return testResult(Request.aClass(type)); } /** * The result of running JUnit on Request {@code request} */ public static PrintableResult testResult(Request request) { return new PrintableResult(new JUnitCore().run(request)); } /** * A result that includes the given {@code failures} */ public PrintableResult(List failures) { this(new FailureList(failures).result()); } private PrintableResult(Result result) { this.result = result; } /** * Returns the number of failures in this result. */ public int failureCount() { return result.getFailures().size(); } @Override public String toString() { ByteArrayOutputStream stream = new ByteArrayOutputStream(); new TextListener(new PrintStream(stream)).testRunFinished(result); return stream.toString(); } }junit4-4.11/src/main/java/org/junit/experimental/results/ResultMatchers.java0000644000175000017500000000421312050524441026563 0ustar ebourgebourgpackage org.junit.experimental.results; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; /** * Matchers on a PrintableResult, to enable JUnit self-tests. * For example: * *
     * assertThat(testResult(HasExpectedException.class), isSuccessful());
     * 
    */ public class ResultMatchers { /** * Matches if the tests are all successful */ public static Matcher isSuccessful() { return failureCountIs(0); } /** * Matches if there are {@code count} failures */ public static Matcher failureCountIs(final int count) { return new TypeSafeMatcher() { public void describeTo(Description description) { description.appendText("has " + count + " failures"); } @Override public boolean matchesSafely(PrintableResult item) { return item.failureCount() == count; } }; } /** * Matches if the result has exactly one failure, and it contains {@code string} */ public static Matcher hasSingleFailureContaining(final String string) { return new BaseMatcher() { public boolean matches(Object item) { return item.toString().contains(string) && failureCountIs(1).matches(item); } public void describeTo(Description description) { description.appendText("has single failure containing " + string); } }; } /** * Matches if the result has one or more failures, and at least one of them * contains {@code string} */ public static Matcher hasFailureContaining(final String string) { return new BaseMatcher() { public boolean matches(Object item) { return item.toString().contains(string); } public void describeTo(Description description) { description.appendText("has failure containing " + string); } }; } } junit4-4.11/src/main/java/org/junit/experimental/results/FailureList.java0000644000175000017500000000135112050524441026041 0ustar ebourgebourgpackage org.junit.experimental.results; import java.util.List; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; class FailureList { private final List failures; public FailureList(List failures) { this.failures = failures; } public Result result() { Result result = new Result(); RunListener listener = result.createListener(); for (Failure failure : failures) { try { listener.testFailure(failure); } catch (Exception e) { throw new RuntimeException("I can't believe this happened"); } } return result; } }junit4-4.11/src/main/java/org/junit/experimental/ParallelComputer.java0000644000175000017500000000415612050524441025376 0ustar ebourgebourgpackage org.junit.experimental; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.junit.runner.Computer; import org.junit.runner.Runner; import org.junit.runners.ParentRunner; import org.junit.runners.model.InitializationError; import org.junit.runners.model.RunnerBuilder; import org.junit.runners.model.RunnerScheduler; public class ParallelComputer extends Computer { private final boolean fClasses; private final boolean fMethods; public ParallelComputer(boolean classes, boolean methods) { fClasses = classes; fMethods = methods; } public static Computer classes() { return new ParallelComputer(true, false); } public static Computer methods() { return new ParallelComputer(false, true); } private static Runner parallelize(Runner runner) { if (runner instanceof ParentRunner) { ((ParentRunner) runner).setScheduler(new RunnerScheduler() { private final ExecutorService fService = Executors.newCachedThreadPool(); public void schedule(Runnable childStatement) { fService.submit(childStatement); } public void finished() { try { fService.shutdown(); fService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { e.printStackTrace(System.err); } } }); } return runner; } @Override public Runner getSuite(RunnerBuilder builder, java.lang.Class[] classes) throws InitializationError { Runner suite = super.getSuite(builder, classes); return fClasses ? parallelize(suite) : suite; } @Override protected Runner getRunner(RunnerBuilder builder, Class testClass) throws Throwable { Runner runner = super.getRunner(builder, testClass); return fMethods ? parallelize(runner) : runner; } } junit4-4.11/src/main/java/org/junit/experimental/runners/0000755000175000017500000000000012050524441022746 5ustar ebourgebourgjunit4-4.11/src/main/java/org/junit/experimental/runners/Enclosed.java0000644000175000017500000000166712050524441025357 0ustar ebourgebourgpackage org.junit.experimental.runners; import org.junit.runners.Suite; import org.junit.runners.model.RunnerBuilder; /** * If you put tests in inner classes, Ant, for example, won't find them. By running the outer class * with Enclosed, the tests in the inner classes will be run. You might put tests in inner classes * to group them for convenience or to share constants. * * So, for example: *
     *  \@RunWith(Enclosed.class)
     *  public class ListTests {
     *      ...useful shared stuff...
     *      public static class OneKindOfListTest {...}
     *      public static class AnotherKind {...}
     *  }
     *  
    * * For a real example, @see org.junit.tests.manipulation.SortableTest. */ public class Enclosed extends Suite { /** * Only called reflectively. Do not use programmatically. */ public Enclosed(Class klass, RunnerBuilder builder) throws Throwable { super(builder, klass, klass.getClasses()); } } junit4-4.11/src/main/java/org/junit/experimental/theories/0000755000175000017500000000000012050524441023074 5ustar ebourgebourgjunit4-4.11/src/main/java/org/junit/experimental/theories/ParametersSuppliedBy.java0000644000175000017500000000040112050524441030036 0ustar ebourgebourgpackage org.junit.experimental.theories; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface ParametersSuppliedBy { Class value(); } junit4-4.11/src/main/java/org/junit/experimental/theories/DataPoint.java0000644000175000017500000000030412050524441025617 0ustar ebourgebourgpackage org.junit.experimental.theories; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface DataPoint { } junit4-4.11/src/main/java/org/junit/experimental/theories/PotentialAssignment.java0000644000175000017500000000172212050524441027731 0ustar ebourgebourgpackage org.junit.experimental.theories; public abstract class PotentialAssignment { public static class CouldNotGenerateValueException extends Exception { private static final long serialVersionUID = 1L; } public static PotentialAssignment forValue(final String name, final Object value) { return new PotentialAssignment() { @Override public Object getValue() throws CouldNotGenerateValueException { return value; } @Override public String toString() { return String.format("[%s]", value); } @Override public String getDescription() throws CouldNotGenerateValueException { return name; } }; } public abstract Object getValue() throws CouldNotGenerateValueException; public abstract String getDescription() throws CouldNotGenerateValueException; } junit4-4.11/src/main/java/org/junit/experimental/theories/internal/0000755000175000017500000000000012050524441024710 5ustar ebourgebourgjunit4-4.11/src/main/java/org/junit/experimental/theories/internal/AllMembersSupplier.java0000644000175000017500000001245112050524441031325 0ustar ebourgebourgpackage org.junit.experimental.theories.internal; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import org.junit.experimental.theories.DataPoint; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.ParameterSignature; import org.junit.experimental.theories.ParameterSupplier; import org.junit.experimental.theories.PotentialAssignment; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.TestClass; /** * Supplies Theory parameters based on all public members of the target class. */ public class AllMembersSupplier extends ParameterSupplier { static class MethodParameterValue extends PotentialAssignment { private final FrameworkMethod fMethod; private MethodParameterValue(FrameworkMethod dataPointMethod) { fMethod = dataPointMethod; } @Override public Object getValue() throws CouldNotGenerateValueException { try { return fMethod.invokeExplosively(null); } catch (IllegalArgumentException e) { throw new RuntimeException( "unexpected: argument length is checked"); } catch (IllegalAccessException e) { throw new RuntimeException( "unexpected: getMethods returned an inaccessible method"); } catch (Throwable e) { throw new CouldNotGenerateValueException(); // do nothing, just look for more values } } @Override public String getDescription() throws CouldNotGenerateValueException { return fMethod.getName(); } } private final TestClass fClass; /** * Constructs a new supplier for {@code type} */ public AllMembersSupplier(TestClass type) { fClass = type; } @Override public List getValueSources(ParameterSignature sig) { List list = new ArrayList(); addFields(sig, list); addSinglePointMethods(sig, list); addMultiPointMethods(sig, list); return list; } private void addMultiPointMethods(ParameterSignature sig, List list) { for (FrameworkMethod dataPointsMethod : fClass .getAnnotatedMethods(DataPoints.class)) { try { addMultiPointArrayValues(sig, dataPointsMethod.getName(), list, dataPointsMethod.invokeExplosively(null)); } catch (Throwable e) { // ignore and move on } } } private void addSinglePointMethods(ParameterSignature sig, List list) { for (FrameworkMethod dataPointMethod : fClass .getAnnotatedMethods(DataPoint.class)) { if (isCorrectlyTyped(sig, dataPointMethod.getType())) { list.add(new MethodParameterValue(dataPointMethod)); } } } private void addFields(ParameterSignature sig, List list) { for (final Field field : fClass.getJavaClass().getFields()) { if (Modifier.isStatic(field.getModifiers())) { Class type = field.getType(); if (sig.canAcceptArrayType(type) && field.getAnnotation(DataPoints.class) != null) { try { addArrayValues(field.getName(), list, getStaticFieldValue(field)); } catch (Throwable e) { // ignore and move on } } else if (sig.canAcceptType(type) && field.getAnnotation(DataPoint.class) != null) { list.add(PotentialAssignment .forValue(field.getName(), getStaticFieldValue(field))); } } } } private void addArrayValues(String name, List list, Object array) { for (int i = 0; i < Array.getLength(array); i++) { list.add(PotentialAssignment.forValue(name + "[" + i + "]", Array.get(array, i))); } } private void addMultiPointArrayValues(ParameterSignature sig, String name, List list, Object array) throws Throwable { for (int i = 0; i < Array.getLength(array); i++) { if (!isCorrectlyTyped(sig, Array.get(array, i).getClass())) { return; } list.add(PotentialAssignment.forValue(name + "[" + i + "]", Array.get(array, i))); } } @SuppressWarnings("deprecation") private boolean isCorrectlyTyped(ParameterSignature parameterSignature, Class type) { return parameterSignature.canAcceptType(type); } private Object getStaticFieldValue(final Field field) { try { return field.get(null); } catch (IllegalArgumentException e) { throw new RuntimeException( "unexpected: field from getClass doesn't exist on object"); } catch (IllegalAccessException e) { throw new RuntimeException( "unexpected: getFields returned an inaccessible field"); } } }junit4-4.11/src/main/java/org/junit/experimental/theories/internal/Assignments.java0000644000175000017500000001115512050524441030051 0ustar ebourgebourgpackage org.junit.experimental.theories.internal; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.junit.experimental.theories.ParameterSignature; import org.junit.experimental.theories.ParameterSupplier; import org.junit.experimental.theories.ParametersSuppliedBy; import org.junit.experimental.theories.PotentialAssignment; import org.junit.experimental.theories.PotentialAssignment.CouldNotGenerateValueException; import org.junit.runners.model.TestClass; /** * A potentially incomplete list of value assignments for a method's formal * parameters */ public class Assignments { private List fAssigned; private final List fUnassigned; private final TestClass fClass; private Assignments(List assigned, List unassigned, TestClass testClass) { fUnassigned = unassigned; fAssigned = assigned; fClass = testClass; } /** * Returns a new assignment list for {@code testMethod}, with no params * assigned. */ public static Assignments allUnassigned(Method testMethod, TestClass testClass) throws Exception { List signatures; signatures = ParameterSignature.signatures(testClass .getOnlyConstructor()); signatures.addAll(ParameterSignature.signatures(testMethod)); return new Assignments(new ArrayList(), signatures, testClass); } public boolean isComplete() { return fUnassigned.size() == 0; } public ParameterSignature nextUnassigned() { return fUnassigned.get(0); } public Assignments assignNext(PotentialAssignment source) { List assigned = new ArrayList( fAssigned); assigned.add(source); return new Assignments(assigned, fUnassigned.subList(1, fUnassigned .size()), fClass); } public Object[] getActualValues(int start, int stop, boolean nullsOk) throws CouldNotGenerateValueException { Object[] values = new Object[stop - start]; for (int i = start; i < stop; i++) { Object value = fAssigned.get(i).getValue(); if (value == null && !nullsOk) { throw new CouldNotGenerateValueException(); } values[i - start] = value; } return values; } public List potentialsForNextUnassigned() throws InstantiationException, IllegalAccessException { ParameterSignature unassigned = nextUnassigned(); return getSupplier(unassigned).getValueSources(unassigned); } public ParameterSupplier getSupplier(ParameterSignature unassigned) throws InstantiationException, IllegalAccessException { ParameterSupplier supplier = getAnnotatedSupplier(unassigned); if (supplier != null) { return supplier; } return new AllMembersSupplier(fClass); } public ParameterSupplier getAnnotatedSupplier(ParameterSignature unassigned) throws InstantiationException, IllegalAccessException { ParametersSuppliedBy annotation = unassigned .findDeepAnnotation(ParametersSuppliedBy.class); if (annotation == null) { return null; } return annotation.value().newInstance(); } public Object[] getConstructorArguments(boolean nullsOk) throws CouldNotGenerateValueException { return getActualValues(0, getConstructorParameterCount(), nullsOk); } public Object[] getMethodArguments(boolean nullsOk) throws CouldNotGenerateValueException { return getActualValues(getConstructorParameterCount(), fAssigned.size(), nullsOk); } public Object[] getAllArguments(boolean nullsOk) throws CouldNotGenerateValueException { return getActualValues(0, fAssigned.size(), nullsOk); } private int getConstructorParameterCount() { List signatures = ParameterSignature .signatures(fClass.getOnlyConstructor()); int constructorParameterCount = signatures.size(); return constructorParameterCount; } public Object[] getArgumentStrings(boolean nullsOk) throws CouldNotGenerateValueException { Object[] values = new Object[fAssigned.size()]; for (int i = 0; i < values.length; i++) { values[i] = fAssigned.get(i).getDescription(); } return values; } }junit4-4.11/src/main/java/org/junit/experimental/theories/internal/ParameterizedAssertionError.java0000644000175000017500000000253712050524441033260 0ustar ebourgebourgpackage org.junit.experimental.theories.internal; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; public class ParameterizedAssertionError extends RuntimeException { private static final long serialVersionUID = 1L; public ParameterizedAssertionError(Throwable targetException, String methodName, Object... params) { super(String.format("%s(%s)", methodName, join(", ", params)), targetException); } @Override public boolean equals(Object obj) { return toString().equals(obj.toString()); } public static String join(String delimiter, Object... params) { return join(delimiter, Arrays.asList(params)); } public static String join(String delimiter, Collection values) { StringBuffer buffer = new StringBuffer(); Iterator iter = values.iterator(); while (iter.hasNext()) { Object next = iter.next(); buffer.append(stringValueOf(next)); if (iter.hasNext()) { buffer.append(delimiter); } } return buffer.toString(); } private static String stringValueOf(Object next) { try { return String.valueOf(next); } catch (Throwable e) { return "[toString failed]"; } } }junit4-4.11/src/main/java/org/junit/experimental/theories/ParameterSignature.java0000644000175000017500000000562612050524441027552 0ustar ebourgebourgpackage org.junit.experimental.theories; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ParameterSignature { public static ArrayList signatures(Method method) { return signatures(method.getParameterTypes(), method .getParameterAnnotations()); } public static List signatures(Constructor constructor) { return signatures(constructor.getParameterTypes(), constructor .getParameterAnnotations()); } private static ArrayList signatures( Class[] parameterTypes, Annotation[][] parameterAnnotations) { ArrayList sigs = new ArrayList(); for (int i = 0; i < parameterTypes.length; i++) { sigs.add(new ParameterSignature(parameterTypes[i], parameterAnnotations[i])); } return sigs; } private final Class type; private final Annotation[] annotations; private ParameterSignature(Class type, Annotation[] annotations) { this.type = type; this.annotations = annotations; } public boolean canAcceptType(Class candidate) { return type.isAssignableFrom(candidate); } public Class getType() { return type; } public List getAnnotations() { return Arrays.asList(annotations); } public boolean canAcceptArrayType(Class type) { return type.isArray() && canAcceptType(type.getComponentType()); } public boolean hasAnnotation(Class type) { return getAnnotation(type) != null; } public T findDeepAnnotation(Class annotationType) { Annotation[] annotations2 = annotations; return findDeepAnnotation(annotations2, annotationType, 3); } private T findDeepAnnotation( Annotation[] annotations, Class annotationType, int depth) { if (depth == 0) { return null; } for (Annotation each : annotations) { if (annotationType.isInstance(each)) { return annotationType.cast(each); } Annotation candidate = findDeepAnnotation(each.annotationType() .getAnnotations(), annotationType, depth - 1); if (candidate != null) { return annotationType.cast(candidate); } } return null; } public T getAnnotation(Class annotationType) { for (Annotation each : getAnnotations()) { if (annotationType.isInstance(each)) { return annotationType.cast(each); } } return null; } }junit4-4.11/src/main/java/org/junit/experimental/theories/Theory.java0000644000175000017500000000035112050524441025210 0ustar ebourgebourgpackage org.junit.experimental.theories; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface Theory { boolean nullsAccepted() default true; }junit4-4.11/src/main/java/org/junit/experimental/theories/Theories.java0000644000175000017500000001721512050524441025527 0ustar ebourgebourgpackage org.junit.experimental.theories; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.experimental.theories.PotentialAssignment.CouldNotGenerateValueException; import org.junit.experimental.theories.internal.Assignments; import org.junit.experimental.theories.internal.ParameterizedAssertionError; import org.junit.internal.AssumptionViolatedException; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement; import org.junit.runners.model.TestClass; public class Theories extends BlockJUnit4ClassRunner { public Theories(Class klass) throws InitializationError { super(klass); } @Override protected void collectInitializationErrors(List errors) { super.collectInitializationErrors(errors); validateDataPointFields(errors); } private void validateDataPointFields(List errors) { Field[] fields = getTestClass().getJavaClass().getDeclaredFields(); for (Field field : fields) { if (field.getAnnotation(DataPoint.class) == null) { continue; } if (!Modifier.isStatic(field.getModifiers())) { errors.add(new Error("DataPoint field " + field.getName() + " must be static")); } if (!Modifier.isPublic(field.getModifiers())) { errors.add(new Error("DataPoint field " + field.getName() + " must be public")); } } } @Override protected void validateConstructor(List errors) { validateOnlyOneConstructor(errors); } @Override protected void validateTestMethods(List errors) { for (FrameworkMethod each : computeTestMethods()) { if (each.getAnnotation(Theory.class) != null) { each.validatePublicVoid(false, errors); } else { each.validatePublicVoidNoArg(false, errors); } } } @Override protected List computeTestMethods() { List testMethods = super.computeTestMethods(); List theoryMethods = getTestClass().getAnnotatedMethods(Theory.class); testMethods.removeAll(theoryMethods); testMethods.addAll(theoryMethods); return testMethods; } @Override public Statement methodBlock(final FrameworkMethod method) { return new TheoryAnchor(method, getTestClass()); } public static class TheoryAnchor extends Statement { private int successes = 0; private FrameworkMethod fTestMethod; private TestClass fTestClass; private List fInvalidParameters = new ArrayList(); public TheoryAnchor(FrameworkMethod method, TestClass testClass) { fTestMethod = method; fTestClass = testClass; } private TestClass getTestClass() { return fTestClass; } @Override public void evaluate() throws Throwable { runWithAssignment(Assignments.allUnassigned( fTestMethod.getMethod(), getTestClass())); if (successes == 0) { Assert .fail("Never found parameters that satisfied method assumptions. Violated assumptions: " + fInvalidParameters); } } protected void runWithAssignment(Assignments parameterAssignment) throws Throwable { if (!parameterAssignment.isComplete()) { runWithIncompleteAssignment(parameterAssignment); } else { runWithCompleteAssignment(parameterAssignment); } } protected void runWithIncompleteAssignment(Assignments incomplete) throws InstantiationException, IllegalAccessException, Throwable { for (PotentialAssignment source : incomplete .potentialsForNextUnassigned()) { runWithAssignment(incomplete.assignNext(source)); } } protected void runWithCompleteAssignment(final Assignments complete) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, Throwable { new BlockJUnit4ClassRunner(getTestClass().getJavaClass()) { @Override protected void collectInitializationErrors( List errors) { // do nothing } @Override public Statement methodBlock(FrameworkMethod method) { final Statement statement = super.methodBlock(method); return new Statement() { @Override public void evaluate() throws Throwable { try { statement.evaluate(); handleDataPointSuccess(); } catch (AssumptionViolatedException e) { handleAssumptionViolation(e); } catch (Throwable e) { reportParameterizedError(e, complete .getArgumentStrings(nullsOk())); } } }; } @Override protected Statement methodInvoker(FrameworkMethod method, Object test) { return methodCompletesWithParameters(method, complete, test); } @Override public Object createTest() throws Exception { return getTestClass().getOnlyConstructor().newInstance( complete.getConstructorArguments(nullsOk())); } }.methodBlock(fTestMethod).evaluate(); } private Statement methodCompletesWithParameters( final FrameworkMethod method, final Assignments complete, final Object freshInstance) { return new Statement() { @Override public void evaluate() throws Throwable { try { final Object[] values = complete.getMethodArguments( nullsOk()); method.invokeExplosively(freshInstance, values); } catch (CouldNotGenerateValueException e) { // ignore } } }; } protected void handleAssumptionViolation(AssumptionViolatedException e) { fInvalidParameters.add(e); } protected void reportParameterizedError(Throwable e, Object... params) throws Throwable { if (params.length == 0) { throw e; } throw new ParameterizedAssertionError(e, fTestMethod.getName(), params); } private boolean nullsOk() { Theory annotation = fTestMethod.getMethod().getAnnotation( Theory.class); if (annotation == null) { return false; } return annotation.nullsAccepted(); } protected void handleDataPointSuccess() { successes++; } } } junit4-4.11/src/main/java/org/junit/experimental/theories/suppliers/0000755000175000017500000000000012050524441025122 5ustar ebourgebourgjunit4-4.11/src/main/java/org/junit/experimental/theories/suppliers/TestedOnSupplier.java0000644000175000017500000000135612050524441031243 0ustar ebourgebourgpackage org.junit.experimental.theories.suppliers; import java.util.ArrayList; import java.util.List; import org.junit.experimental.theories.ParameterSignature; import org.junit.experimental.theories.ParameterSupplier; import org.junit.experimental.theories.PotentialAssignment; public class TestedOnSupplier extends ParameterSupplier { @Override public List getValueSources(ParameterSignature sig) { List list = new ArrayList(); TestedOn testedOn = sig.getAnnotation(TestedOn.class); int[] ints = testedOn.ints(); for (final int i : ints) { list.add(PotentialAssignment.forValue("ints", i)); } return list; } } junit4-4.11/src/main/java/org/junit/experimental/theories/suppliers/TestedOn.java0000644000175000017500000000051212050524441027510 0ustar ebourgebourgpackage org.junit.experimental.theories.suppliers; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import org.junit.experimental.theories.ParametersSuppliedBy; @ParametersSuppliedBy(TestedOnSupplier.class) @Retention(RetentionPolicy.RUNTIME) public @interface TestedOn { int[] ints(); } junit4-4.11/src/main/java/org/junit/experimental/theories/DataPoints.java0000644000175000017500000000030512050524441026003 0ustar ebourgebourgpackage org.junit.experimental.theories; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface DataPoints { } junit4-4.11/src/main/java/org/junit/experimental/theories/ParameterSupplier.java0000644000175000017500000000030512050524441027401 0ustar ebourgebourgpackage org.junit.experimental.theories; import java.util.List; public abstract class ParameterSupplier { public abstract List getValueSources(ParameterSignature sig); } junit4-4.11/src/main/java/org/junit/experimental/categories/0000755000175000017500000000000012050524441023377 5ustar ebourgebourgjunit4-4.11/src/main/java/org/junit/experimental/categories/Category.java0000644000175000017500000000160712050524441026023 0ustar ebourgebourgpackage org.junit.experimental.categories; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Marks a test class or test method as belonging to one or more categories of tests. * The value is an array of arbitrary classes. * * This annotation is only interpreted by the Categories runner (at present). * * For example: *
     * public interface FastTests {}
     * public interface SlowTests {}
     *
     * public static class A {
     * @Test
     * public void a() {
     * fail();
     * }
     *
     * @Category(SlowTests.class)
     * @Test
     * public void b() {
     * }
     * }
     *
     * @Category({SlowTests.class, FastTests.class})
     * public static class B {
     * @Test
     * public void c() {
     *
     * }
     * }
     * 
    * * For more usage, see code example on {@link Categories}. */ @Retention(RetentionPolicy.RUNTIME) public @interface Category { Class[] value(); }junit4-4.11/src/main/java/org/junit/experimental/categories/Categories.java0000644000175000017500000001526112050524441026334 0ustar ebourgebourgpackage org.junit.experimental.categories; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.runner.Description; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runners.Suite; import org.junit.runners.model.InitializationError; import org.junit.runners.model.RunnerBuilder; /** * From a given set of test classes, runs only the classes and methods that are * annotated with either the category given with the @IncludeCategory * annotation, or a subtype of that category. * * Note that, for now, annotating suites with {@code @Category} has no effect. * Categories must be annotated on the direct method or class. * * Example: * *
     * public interface FastTests {
     * }
     *
     * public interface SlowTests {
     * }
     *
     * public static class A {
     *  @Test
     *  public void a() {
     *      fail();
     *     }
     *
     *  @Category(SlowTests.class)
     *  @Test
     *  public void b() {
     *     }
     * }
     *
     * @Category( { SlowTests.class, FastTests.class })
     * public static class B {
     *  @Test
     *  public void c() {
     *
     *     }
     * }
     *
     * @RunWith(Categories.class)
     * @IncludeCategory(SlowTests.class)
     * @SuiteClasses( { A.class, B.class })
     * // Note that Categories is a kind of Suite
     * public static class SlowTestSuite {
     * }
     * 
    */ public class Categories extends Suite { // the way filters are implemented makes this unnecessarily complicated, // buggy, and difficult to specify. A new way of handling filters could // someday enable a better new implementation. // https://github.com/KentBeck/junit/issues/issue/172 @Retention(RetentionPolicy.RUNTIME) public @interface IncludeCategory { public Class value(); } @Retention(RetentionPolicy.RUNTIME) public @interface ExcludeCategory { public Class value(); } public static class CategoryFilter extends Filter { public static CategoryFilter include(Class categoryType) { return new CategoryFilter(categoryType, null); } private final Class fIncluded; private final Class fExcluded; public CategoryFilter(Class includedCategory, Class excludedCategory) { fIncluded = includedCategory; fExcluded = excludedCategory; } @Override public String describe() { return "category " + fIncluded; } @Override public boolean shouldRun(Description description) { if (hasCorrectCategoryAnnotation(description)) { return true; } for (Description each : description.getChildren()) { if (shouldRun(each)) { return true; } } return false; } private boolean hasCorrectCategoryAnnotation(Description description) { List> categories = categories(description); if (categories.isEmpty()) { return fIncluded == null; } for (Class each : categories) { if (fExcluded != null && fExcluded.isAssignableFrom(each)) { return false; } } for (Class each : categories) { if (fIncluded == null || fIncluded.isAssignableFrom(each)) { return true; } } return false; } private List> categories(Description description) { ArrayList> categories = new ArrayList>(); categories.addAll(Arrays.asList(directCategories(description))); categories.addAll(Arrays.asList(directCategories(parentDescription(description)))); return categories; } private Description parentDescription(Description description) { Class testClass = description.getTestClass(); if (testClass == null) { return null; } return Description.createSuiteDescription(testClass); } private Class[] directCategories(Description description) { if (description == null) { return new Class[0]; } Category annotation = description.getAnnotation(Category.class); if (annotation == null) { return new Class[0]; } return annotation.value(); } } public Categories(Class klass, RunnerBuilder builder) throws InitializationError { super(klass, builder); try { filter(new CategoryFilter(getIncludedCategory(klass), getExcludedCategory(klass))); } catch (NoTestsRemainException e) { throw new InitializationError(e); } assertNoCategorizedDescendentsOfUncategorizeableParents(getDescription()); } private Class getIncludedCategory(Class klass) { IncludeCategory annotation = klass.getAnnotation(IncludeCategory.class); return annotation == null ? null : annotation.value(); } private Class getExcludedCategory(Class klass) { ExcludeCategory annotation = klass.getAnnotation(ExcludeCategory.class); return annotation == null ? null : annotation.value(); } private void assertNoCategorizedDescendentsOfUncategorizeableParents(Description description) throws InitializationError { if (!canHaveCategorizedChildren(description)) { assertNoDescendantsHaveCategoryAnnotations(description); } for (Description each : description.getChildren()) { assertNoCategorizedDescendentsOfUncategorizeableParents(each); } } private void assertNoDescendantsHaveCategoryAnnotations(Description description) throws InitializationError { for (Description each : description.getChildren()) { if (each.getAnnotation(Category.class) != null) { throw new InitializationError("Category annotations on Parameterized classes are not supported on individual methods."); } assertNoDescendantsHaveCategoryAnnotations(each); } } // If children have names like [0], our current magical category code can't determine their // parentage. private static boolean canHaveCategorizedChildren(Description description) { for (Description each : description.getChildren()) { if (each.getTestClass() == null) { return false; } } return true; } }junit4-4.11/src/main/java/org/junit/Rule.java0000644000175000017500000000465212050524441020336 0ustar ebourgebourgpackage org.junit; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotates fields that reference rules or methods that return a rule. A field must be public, not * static, and a subtype of {@link org.junit.rules.TestRule} (preferred) or * {@link org.junit.rules.MethodRule}. A method must be public, not static, * and must return a subtype of {@link org.junit.rules.TestRule} (preferred) or * {@link org.junit.rules.MethodRule}.

    * * The {@link org.junit.runners.model.Statement} passed * to the {@link org.junit.rules.TestRule} will run any {@link Before} methods, * then the {@link Test} method, and finally any {@link After} methods, * throwing an exception if any of these fail. If there are multiple * annotated {@link Rule}s on a class, they will be applied in order of fields first, then methods. * However, if there are mutliple fields (or methods) they will be applied in an order * that depends on your JVM's implementation of the reflection API, which is * undefined, in general. Rules defined by fields will always be applied * before Rules defined by methods.

    * * For example, here is a test class that creates a temporary folder before * each test method, and deletes it after each: * *

     * public static class HasTempFolder {
     *     @Rule
     *     public TemporaryFolder folder= new TemporaryFolder();
     *
     *     @Test
     *     public void testUsingTempFolder() throws IOException {
     *         File createdFile= folder.newFile("myfile.txt");
     *         File createdFolder= folder.newFolder("subfolder");
     *         // ...
     *     }
     * }
     * 
    * * And the same using a method. * *
     * public static class HasTempFolder {
     *     private TemporaryFolder folder= new TemporaryFolder();
     *
     *     @Rule
     *     public TemporaryFolder getFolder() {
     *         return folder;
     *     }
     *
     *     @Test
     *     public void testUsingTempFolder() throws IOException {
     *         File createdFile= folder.newFile("myfile.txt");
     *         File createdFolder= folder.newFolder("subfolder");
     *         // ...
     *     }
     * }
     * 
    * * For more information and more examples, see * {@link org.junit.rules.TestRule}. * * @since 4.7 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD}) public @interface Rule { }junit4-4.11/src/main/java/org/junit/internal/0000755000175000017500000000000012050524441020371 5ustar ebourgebourgjunit4-4.11/src/main/java/org/junit/internal/MethodSorter.java0000644000175000017500000000454612050524441023664 0ustar ebourgebourgpackage org.junit.internal; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Comparator; import org.junit.FixMethodOrder; public class MethodSorter { /** * DEFAULT sort order */ public static Comparator DEFAULT = new Comparator() { public int compare(Method m1, Method m2) { int i1 = m1.getName().hashCode(); int i2 = m2.getName().hashCode(); if (i1 != i2) { return i1 < i2 ? -1 : 1; } return NAME_ASCENDING.compare(m1, m2); } }; /** * Method name ascending lexicographic sort order, with {@link Method#toString()} as a tiebreaker */ public static Comparator NAME_ASCENDING = new Comparator() { public int compare(Method m1, Method m2) { final int comparison = m1.getName().compareTo(m2.getName()); if (comparison != 0) { return comparison; } return m1.toString().compareTo(m2.toString()); } }; /** * Gets declared methods of a class in a predictable order, unless @FixMethodOrder(MethodSorters.JVM) is specified. * * Using the JVM order is unwise since the Java platform does not * specify any particular order, and in fact JDK 7 returns a more or less * random order; well-written test code would not assume any order, but some * does, and a predictable failure is better than a random failure on * certain platforms. By default, uses an unspecified but deterministic order. * * @param clazz a class * @return same as {@link Class#getDeclaredMethods} but sorted * @see JDK * (non-)bug #7023180 */ public static Method[] getDeclaredMethods(Class clazz) { Comparator comparator = getSorter(clazz.getAnnotation(FixMethodOrder.class)); Method[] methods = clazz.getDeclaredMethods(); if (comparator != null) { Arrays.sort(methods, comparator); } return methods; } private MethodSorter() { } private static Comparator getSorter(FixMethodOrder fixMethodOrder) { if (fixMethodOrder == null) { return DEFAULT; } return fixMethodOrder.value().getComparator(); } } junit4-4.11/src/main/java/org/junit/internal/builders/0000755000175000017500000000000012050524441022202 5ustar ebourgebourgjunit4-4.11/src/main/java/org/junit/internal/builders/SuiteMethodBuilder.java0000644000175000017500000000117512050524441026612 0ustar ebourgebourgpackage org.junit.internal.builders; import org.junit.internal.runners.SuiteMethod; import org.junit.runner.Runner; import org.junit.runners.model.RunnerBuilder; public class SuiteMethodBuilder extends RunnerBuilder { @Override public Runner runnerForClass(Class each) throws Throwable { if (hasSuiteMethod(each)) { return new SuiteMethod(each); } return null; } public boolean hasSuiteMethod(Class testClass) { try { testClass.getMethod("suite"); } catch (NoSuchMethodException e) { return false; } return true; } }junit4-4.11/src/main/java/org/junit/internal/builders/NullBuilder.java0000644000175000017500000000042312050524441025265 0ustar ebourgebourgpackage org.junit.internal.builders; import org.junit.runner.Runner; import org.junit.runners.model.RunnerBuilder; public class NullBuilder extends RunnerBuilder { @Override public Runner runnerForClass(Class each) throws Throwable { return null; } }junit4-4.11/src/main/java/org/junit/internal/builders/IgnoredClassRunner.java0000644000175000017500000000110512050524441026611 0ustar ebourgebourgpackage org.junit.internal.builders; import org.junit.runner.Description; import org.junit.runner.Runner; import org.junit.runner.notification.RunNotifier; public class IgnoredClassRunner extends Runner { private final Class fTestClass; public IgnoredClassRunner(Class testClass) { fTestClass = testClass; } @Override public void run(RunNotifier notifier) { notifier.fireTestIgnored(getDescription()); } @Override public Description getDescription() { return Description.createSuiteDescription(fTestClass); } }junit4-4.11/src/main/java/org/junit/internal/builders/IgnoredBuilder.java0000644000175000017500000000064012050524441025743 0ustar ebourgebourgpackage org.junit.internal.builders; import org.junit.Ignore; import org.junit.runner.Runner; import org.junit.runners.model.RunnerBuilder; public class IgnoredBuilder extends RunnerBuilder { @Override public Runner runnerForClass(Class testClass) { if (testClass.getAnnotation(Ignore.class) != null) { return new IgnoredClassRunner(testClass); } return null; } }junit4-4.11/src/main/java/org/junit/internal/builders/JUnit3Builder.java0000644000175000017500000000106412050524441025471 0ustar ebourgebourgpackage org.junit.internal.builders; import org.junit.internal.runners.JUnit38ClassRunner; import org.junit.runner.Runner; import org.junit.runners.model.RunnerBuilder; public class JUnit3Builder extends RunnerBuilder { @Override public Runner runnerForClass(Class testClass) throws Throwable { if (isPre4Test(testClass)) { return new JUnit38ClassRunner(testClass); } return null; } boolean isPre4Test(Class testClass) { return junit.framework.TestCase.class.isAssignableFrom(testClass); } }junit4-4.11/src/main/java/org/junit/internal/builders/JUnit4Builder.java0000644000175000017500000000055412050524441025475 0ustar ebourgebourgpackage org.junit.internal.builders; import org.junit.runner.Runner; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.RunnerBuilder; public class JUnit4Builder extends RunnerBuilder { @Override public Runner runnerForClass(Class testClass) throws Throwable { return new BlockJUnit4ClassRunner(testClass); } }junit4-4.11/src/main/java/org/junit/internal/builders/AllDefaultPossibilitiesBuilder.java0000644000175000017500000000273712050524441031145 0ustar ebourgebourgpackage org.junit.internal.builders; import java.util.Arrays; import java.util.List; import org.junit.runner.Runner; import org.junit.runners.model.RunnerBuilder; public class AllDefaultPossibilitiesBuilder extends RunnerBuilder { private final boolean fCanUseSuiteMethod; public AllDefaultPossibilitiesBuilder(boolean canUseSuiteMethod) { fCanUseSuiteMethod = canUseSuiteMethod; } @Override public Runner runnerForClass(Class testClass) throws Throwable { List builders = Arrays.asList( ignoredBuilder(), annotatedBuilder(), suiteMethodBuilder(), junit3Builder(), junit4Builder()); for (RunnerBuilder each : builders) { Runner runner = each.safeRunnerForClass(testClass); if (runner != null) { return runner; } } return null; } protected JUnit4Builder junit4Builder() { return new JUnit4Builder(); } protected JUnit3Builder junit3Builder() { return new JUnit3Builder(); } protected AnnotatedBuilder annotatedBuilder() { return new AnnotatedBuilder(this); } protected IgnoredBuilder ignoredBuilder() { return new IgnoredBuilder(); } protected RunnerBuilder suiteMethodBuilder() { if (fCanUseSuiteMethod) { return new SuiteMethodBuilder(); } return new NullBuilder(); } }junit4-4.11/src/main/java/org/junit/internal/builders/AnnotatedBuilder.java0000644000175000017500000000313112050524441026267 0ustar ebourgebourgpackage org.junit.internal.builders; import org.junit.runner.RunWith; import org.junit.runner.Runner; import org.junit.runners.model.InitializationError; import org.junit.runners.model.RunnerBuilder; public class AnnotatedBuilder extends RunnerBuilder { private static final String CONSTRUCTOR_ERROR_FORMAT = "Custom runner class %s should have a public constructor with signature %s(Class testClass)"; private RunnerBuilder fSuiteBuilder; public AnnotatedBuilder(RunnerBuilder suiteBuilder) { fSuiteBuilder = suiteBuilder; } @Override public Runner runnerForClass(Class testClass) throws Exception { RunWith annotation = testClass.getAnnotation(RunWith.class); if (annotation != null) { return buildRunner(annotation.value(), testClass); } return null; } public Runner buildRunner(Class runnerClass, Class testClass) throws Exception { try { return runnerClass.getConstructor(Class.class).newInstance( new Object[]{testClass}); } catch (NoSuchMethodException e) { try { return runnerClass.getConstructor(Class.class, RunnerBuilder.class).newInstance( new Object[]{testClass, fSuiteBuilder}); } catch (NoSuchMethodException e2) { String simpleName = runnerClass.getSimpleName(); throw new InitializationError(String.format( CONSTRUCTOR_ERROR_FORMAT, simpleName, simpleName)); } } } }junit4-4.11/src/main/java/org/junit/internal/ComparisonCriteria.java0000644000175000017500000000547112050524441025040 0ustar ebourgebourgpackage org.junit.internal; import java.lang.reflect.Array; import org.junit.Assert; /** * Defines criteria for finding two items "equal enough". Concrete subclasses * may demand exact equality, or, for example, equality within a given delta. */ public abstract class ComparisonCriteria { /** * Asserts that two arrays are equal, according to the criteria defined by * the concrete subclass. If they are not, an {@link AssertionError} is * thrown with the given message. If expecteds and * actuals are null, they are considered equal. * * @param message the identifying message for the {@link AssertionError} ( * null okay) * @param expecteds Object array or array of arrays (multi-dimensional array) with * expected values. * @param actuals Object array or array of arrays (multi-dimensional array) with * actual values */ public void arrayEquals(String message, Object expecteds, Object actuals) throws ArrayComparisonFailure { if (expecteds == actuals) { return; } String header = message == null ? "" : message + ": "; int expectedsLength = assertArraysAreSameLength(expecteds, actuals, header); for (int i = 0; i < expectedsLength; i++) { Object expected = Array.get(expecteds, i); Object actual = Array.get(actuals, i); if (isArray(expected) && isArray(actual)) { try { arrayEquals(message, expected, actual); } catch (ArrayComparisonFailure e) { e.addDimension(i); throw e; } } else { try { assertElementsEqual(expected, actual); } catch (AssertionError e) { throw new ArrayComparisonFailure(header, e, i); } } } } private boolean isArray(Object expected) { return expected != null && expected.getClass().isArray(); } private int assertArraysAreSameLength(Object expecteds, Object actuals, String header) { if (expecteds == null) { Assert.fail(header + "expected array was null"); } if (actuals == null) { Assert.fail(header + "actual array was null"); } int actualsLength = Array.getLength(actuals); int expectedsLength = Array.getLength(expecteds); if (actualsLength != expectedsLength) { Assert.fail(header + "array lengths differed, expected.length=" + expectedsLength + " actual.length=" + actualsLength); } return expectedsLength; } protected abstract void assertElementsEqual(Object expected, Object actual); } junit4-4.11/src/main/java/org/junit/internal/ExactComparisonCriteria.java0000644000175000017500000000040712050524441026017 0ustar ebourgebourgpackage org.junit.internal; import org.junit.Assert; public class ExactComparisonCriteria extends ComparisonCriteria { @Override protected void assertElementsEqual(Object expected, Object actual) { Assert.assertEquals(expected, actual); } } junit4-4.11/src/main/java/org/junit/internal/requests/0000755000175000017500000000000012050524441022244 5ustar ebourgebourgjunit4-4.11/src/main/java/org/junit/internal/requests/package-info.java0000644000175000017500000000017612050524441025437 0ustar ebourgebourg/** * Provides implementations of {@link org.junit.runner.Request}. * * @since 4.0 */ package org.junit.internal.requests;junit4-4.11/src/main/java/org/junit/internal/requests/ClassRequest.java0000644000175000017500000000162412050524441025530 0ustar ebourgebourgpackage org.junit.internal.requests; import org.junit.internal.builders.AllDefaultPossibilitiesBuilder; import org.junit.runner.Request; import org.junit.runner.Runner; public class ClassRequest extends Request { private final Object fRunnerLock = new Object(); private final Class fTestClass; private final boolean fCanUseSuiteMethod; private Runner fRunner; public ClassRequest(Class testClass, boolean canUseSuiteMethod) { fTestClass = testClass; fCanUseSuiteMethod = canUseSuiteMethod; } public ClassRequest(Class testClass) { this(testClass, true); } @Override public Runner getRunner() { synchronized (fRunnerLock) { if (fRunner == null) { fRunner = new AllDefaultPossibilitiesBuilder(fCanUseSuiteMethod).safeRunnerForClass(fTestClass); } return fRunner; } } }junit4-4.11/src/main/java/org/junit/internal/requests/SortingRequest.java0000644000175000017500000000124212050524441026104 0ustar ebourgebourgpackage org.junit.internal.requests; import java.util.Comparator; import org.junit.runner.Description; import org.junit.runner.Request; import org.junit.runner.Runner; import org.junit.runner.manipulation.Sorter; public class SortingRequest extends Request { private final Request fRequest; private final Comparator fComparator; public SortingRequest(Request request, Comparator comparator) { fRequest = request; fComparator = comparator; } @Override public Runner getRunner() { Runner runner = fRequest.getRunner(); new Sorter(fComparator).apply(runner); return runner; } } junit4-4.11/src/main/java/org/junit/internal/requests/FilterRequest.java0000644000175000017500000000232512050524441025707 0ustar ebourgebourgpackage org.junit.internal.requests; import org.junit.internal.runners.ErrorReportingRunner; import org.junit.runner.Request; import org.junit.runner.Runner; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.NoTestsRemainException; /** * A filtered {@link Request}. */ public final class FilterRequest extends Request { private final Request fRequest; private final Filter fFilter; /** * Creates a filtered Request * * @param classRequest a {@link Request} describing your Tests * @param filter {@link Filter} to apply to the Tests described in * classRequest */ public FilterRequest(Request classRequest, Filter filter) { fRequest = classRequest; fFilter = filter; } @Override public Runner getRunner() { try { Runner runner = fRequest.getRunner(); fFilter.apply(runner); return runner; } catch (NoTestsRemainException e) { return new ErrorReportingRunner(Filter.class, new Exception(String .format("No tests found matching %s from %s", fFilter .describe(), fRequest.toString()))); } } }junit4-4.11/src/main/java/org/junit/internal/InexactComparisonCriteria.java0000644000175000017500000000121112050524441026340 0ustar ebourgebourgpackage org.junit.internal; import org.junit.Assert; public class InexactComparisonCriteria extends ComparisonCriteria { public Object fDelta; public InexactComparisonCriteria(double delta) { fDelta = delta; } public InexactComparisonCriteria(float delta) { fDelta = delta; } @Override protected void assertElementsEqual(Object expected, Object actual) { if (expected instanceof Double) { Assert.assertEquals((Double) expected, (Double) actual, (Double) fDelta); } else { Assert.assertEquals((Float) expected, (Float) actual, (Float) fDelta); } } }junit4-4.11/src/main/java/org/junit/internal/TextListener.java0000644000175000017500000000532412050524441023672 0ustar ebourgebourgpackage org.junit.internal; import java.io.PrintStream; import java.text.NumberFormat; import java.util.List; import org.junit.runner.Description; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; public class TextListener extends RunListener { private final PrintStream fWriter; public TextListener(JUnitSystem system) { this(system.out()); } public TextListener(PrintStream writer) { this.fWriter = writer; } @Override public void testRunFinished(Result result) { printHeader(result.getRunTime()); printFailures(result); printFooter(result); } @Override public void testStarted(Description description) { fWriter.append('.'); } @Override public void testFailure(Failure failure) { fWriter.append('E'); } @Override public void testIgnored(Description description) { fWriter.append('I'); } /* * Internal methods */ private PrintStream getWriter() { return fWriter; } protected void printHeader(long runTime) { getWriter().println(); getWriter().println("Time: " + elapsedTimeAsString(runTime)); } protected void printFailures(Result result) { List failures = result.getFailures(); if (failures.size() == 0) { return; } if (failures.size() == 1) { getWriter().println("There was " + failures.size() + " failure:"); } else { getWriter().println("There were " + failures.size() + " failures:"); } int i = 1; for (Failure each : failures) { printFailure(each, "" + i++); } } protected void printFailure(Failure each, String prefix) { getWriter().println(prefix + ") " + each.getTestHeader()); getWriter().print(each.getTrace()); } protected void printFooter(Result result) { if (result.wasSuccessful()) { getWriter().println(); getWriter().print("OK"); getWriter().println(" (" + result.getRunCount() + " test" + (result.getRunCount() == 1 ? "" : "s") + ")"); } else { getWriter().println(); getWriter().println("FAILURES!!!"); getWriter().println("Tests run: " + result.getRunCount() + ", Failures: " + result.getFailureCount()); } getWriter().println(); } /** * Returns the formatted string of the elapsed time. Duplicated from * BaseTestRunner. Fix it. */ protected String elapsedTimeAsString(long runTime) { return NumberFormat.getInstance().format((double) runTime / 1000); } } junit4-4.11/src/main/java/org/junit/internal/matchers/0000755000175000017500000000000012050524441022177 5ustar ebourgebourgjunit4-4.11/src/main/java/org/junit/internal/matchers/StacktracePrintingMatcher.java0000644000175000017500000000327512050524441030154 0ustar ebourgebourgpackage org.junit.internal.matchers; import java.io.PrintWriter; import java.io.StringWriter; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; /** * A matcher that delegates to throwableMatcher and in addition appends the * stacktrace of the actual Throwable in case of a mismatch. */ public class StacktracePrintingMatcher extends org.hamcrest.TypeSafeMatcher { private final Matcher fThrowableMatcher; public StacktracePrintingMatcher(Matcher throwableMatcher) { fThrowableMatcher = throwableMatcher; } public void describeTo(Description description) { fThrowableMatcher.describeTo(description); } @Override protected boolean matchesSafely(T item) { return fThrowableMatcher.matches(item); } @Override protected void describeMismatchSafely(T item, Description description) { fThrowableMatcher.describeMismatch(item, description); description.appendText("\nStacktrace was: "); description.appendText(readStacktrace(item)); } private String readStacktrace(Throwable throwable) { StringWriter stringWriter = new StringWriter(); throwable.printStackTrace(new PrintWriter(stringWriter)); return stringWriter.toString(); } @Factory public static Matcher isThrowable( Matcher throwableMatcher) { return new StacktracePrintingMatcher(throwableMatcher); } @Factory public static Matcher isException( Matcher exceptionMatcher) { return new StacktracePrintingMatcher(exceptionMatcher); } } junit4-4.11/src/main/java/org/junit/internal/matchers/TypeSafeMatcher.java0000644000175000017500000000376212050524441026076 0ustar ebourgebourgpackage org.junit.internal.matchers; import java.lang.reflect.Method; import org.hamcrest.BaseMatcher; import org.junit.internal.MethodSorter; /** * Convenient base class for Matchers that require a non-null value of a specific type. * This simply implements the null check, checks the type and then casts. * * @author Joe Walnes * @deprecated Please use {@link org.hamcrest.TypeSafeMatcher}. */ @Deprecated public abstract class TypeSafeMatcher extends BaseMatcher { private Class expectedType; /** * Subclasses should implement this. The item will already have been checked for * the specific type and will never be null. */ public abstract boolean matchesSafely(T item); protected TypeSafeMatcher() { expectedType = findExpectedType(getClass()); } private static Class findExpectedType(Class fromClass) { for (Class c = fromClass; c != Object.class; c = c.getSuperclass()) { for (Method method : MethodSorter.getDeclaredMethods(c)) { if (isMatchesSafelyMethod(method)) { return method.getParameterTypes()[0]; } } } throw new Error("Cannot determine correct type for matchesSafely() method."); } private static boolean isMatchesSafelyMethod(Method method) { return method.getName().equals("matchesSafely") && method.getParameterTypes().length == 1 && !method.isSynthetic(); } protected TypeSafeMatcher(Class expectedType) { this.expectedType = expectedType; } /** * Method made final to prevent accidental override. * If you need to override this, there's no point on extending TypeSafeMatcher. * Instead, extend the {@link BaseMatcher}. */ @SuppressWarnings({"unchecked"}) public final boolean matches(Object item) { return item != null && expectedType.isInstance(item) && matchesSafely((T) item); } } junit4-4.11/src/main/java/org/junit/internal/matchers/ThrowableCauseMatcher.java0000644000175000017500000000202412050524441027254 0ustar ebourgebourgpackage org.junit.internal.matchers; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; public class ThrowableCauseMatcher extends TypeSafeMatcher { private final Matcher fMatcher; public ThrowableCauseMatcher(Matcher matcher) { fMatcher = matcher; } public void describeTo(Description description) { description.appendText("exception with cause "); description.appendDescriptionOf(fMatcher); } @Override protected boolean matchesSafely(T item) { return fMatcher.matches(item.getCause()); } @Override protected void describeMismatchSafely(T item, Description description) { description.appendText("cause "); fMatcher.describeMismatch(item.getCause(), description); } @Factory public static Matcher hasCause(final Matcher matcher) { return new ThrowableCauseMatcher(matcher); } }junit4-4.11/src/main/java/org/junit/internal/matchers/ThrowableMessageMatcher.java0000644000175000017500000000206312050524441027603 0ustar ebourgebourgpackage org.junit.internal.matchers; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; public class ThrowableMessageMatcher extends TypeSafeMatcher { private final Matcher fMatcher; public ThrowableMessageMatcher(Matcher matcher) { fMatcher = matcher; } public void describeTo(Description description) { description.appendText("exception with message "); description.appendDescriptionOf(fMatcher); } @Override protected boolean matchesSafely(T item) { return fMatcher.matches(item.getMessage()); } @Override protected void describeMismatchSafely(T item, Description description) { description.appendText("message "); fMatcher.describeMismatch(item.getMessage(), description); } @Factory public static Matcher hasMessage(final Matcher matcher) { return new ThrowableMessageMatcher(matcher); } }junit4-4.11/src/main/java/org/junit/internal/runners/0000755000175000017500000000000012050524441022065 5ustar ebourgebourgjunit4-4.11/src/main/java/org/junit/internal/runners/package-info.java0000644000175000017500000000017312050524441025255 0ustar ebourgebourg/** * Provides implementations of {@link org.junit.runner.Runner} * * @since 4.0 */ package org.junit.internal.runners;junit4-4.11/src/main/java/org/junit/internal/runners/MethodValidator.java0000644000175000017500000000636012050524441026023 0ustar ebourgebourgpackage org.junit.internal.runners; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runners.BlockJUnit4ClassRunner; /** * @deprecated Included for backwards compatibility with JUnit 4.4. Will be * removed in the next release. Please use * {@link BlockJUnit4ClassRunner} in place of {@link JUnit4ClassRunner}. */ @Deprecated public class MethodValidator { private final List fErrors = new ArrayList(); private TestClass fTestClass; public MethodValidator(TestClass testClass) { fTestClass = testClass; } public void validateInstanceMethods() { validateTestMethods(After.class, false); validateTestMethods(Before.class, false); validateTestMethods(Test.class, false); List methods = fTestClass.getAnnotatedMethods(Test.class); if (methods.size() == 0) { fErrors.add(new Exception("No runnable methods")); } } public void validateStaticMethods() { validateTestMethods(BeforeClass.class, true); validateTestMethods(AfterClass.class, true); } public List validateMethodsForDefaultRunner() { validateNoArgConstructor(); validateStaticMethods(); validateInstanceMethods(); return fErrors; } public void assertValid() throws InitializationError { if (!fErrors.isEmpty()) { throw new InitializationError(fErrors); } } public void validateNoArgConstructor() { try { fTestClass.getConstructor(); } catch (Exception e) { fErrors.add(new Exception("Test class should have public zero-argument constructor", e)); } } private void validateTestMethods(Class annotation, boolean isStatic) { List methods = fTestClass.getAnnotatedMethods(annotation); for (Method each : methods) { if (Modifier.isStatic(each.getModifiers()) != isStatic) { String state = isStatic ? "should" : "should not"; fErrors.add(new Exception("Method " + each.getName() + "() " + state + " be static")); } if (!Modifier.isPublic(each.getDeclaringClass().getModifiers())) { fErrors.add(new Exception("Class " + each.getDeclaringClass().getName() + " should be public")); } if (!Modifier.isPublic(each.getModifiers())) { fErrors.add(new Exception("Method " + each.getName() + " should be public")); } if (each.getReturnType() != Void.TYPE) { fErrors.add(new Exception("Method " + each.getName() + " should be void")); } if (each.getParameterTypes().length != 0) { fErrors.add(new Exception("Method " + each.getName() + " should have no parameters")); } } } } junit4-4.11/src/main/java/org/junit/internal/runners/rules/0000755000175000017500000000000012050524441023217 5ustar ebourgebourgjunit4-4.11/src/main/java/org/junit/internal/runners/rules/RuleFieldValidator.java0000644000175000017500000001014412050524441027603 0ustar ebourgebourgpackage org.junit.internal.runners.rules; import java.lang.annotation.Annotation; import java.util.List; import org.junit.ClassRule; import org.junit.Rule; import org.junit.rules.MethodRule; import org.junit.rules.TestRule; import org.junit.runners.model.FrameworkMember; import org.junit.runners.model.TestClass; /** * A RuleFieldValidator validates the rule fields of a * {@link org.junit.runners.model.TestClass}. All reasons for rejecting the * {@code TestClass} are written to a list of errors. * * There are four slightly different validators. The {@link #CLASS_RULE_VALIDATOR} * validates fields with a {@link ClassRule} annotation and the * {@link #RULE_VALIDATOR} validates fields with a {@link Rule} annotation. * * The {@link #CLASS_RULE_METHOD_VALIDATOR} * validates methods with a {@link ClassRule} annotation and the * {@link #RULE_METHOD_VALIDATOR} validates methods with a {@link Rule} annotation. */ public enum RuleFieldValidator { /** * Validates fields with a {@link ClassRule} annotation. */ CLASS_RULE_VALIDATOR(ClassRule.class, false, true), /** * Validates fields with a {@link Rule} annotation. */ RULE_VALIDATOR(Rule.class, false, false), /** * Validates methods with a {@link ClassRule} annotation. */ CLASS_RULE_METHOD_VALIDATOR(ClassRule.class, true, true), /** * Validates methods with a {@link Rule} annotation. */ RULE_METHOD_VALIDATOR(Rule.class, true, false); private final Class fAnnotation; private final boolean fStaticMembers; private final boolean fMethods; private RuleFieldValidator(Class annotation, boolean methods, boolean fStaticMembers) { this.fAnnotation = annotation; this.fStaticMembers = fStaticMembers; this.fMethods = methods; } /** * Validate the {@link org.junit.runners.model.TestClass} and adds reasons * for rejecting the class to a list of errors. * * @param target the {@code TestClass} to validate. * @param errors the list of errors. */ public void validate(TestClass target, List errors) { List> members = fMethods ? target.getAnnotatedMethods(fAnnotation) : target.getAnnotatedFields(fAnnotation); for (FrameworkMember each : members) { validateMember(each, errors); } } private void validateMember(FrameworkMember member, List errors) { validateStatic(member, errors); validatePublic(member, errors); validateTestRuleOrMethodRule(member, errors); } private void validateStatic(FrameworkMember member, List errors) { if (fStaticMembers && !member.isStatic()) { addError(errors, member, "must be static."); } if (!fStaticMembers && member.isStatic()) { addError(errors, member, "must not be static."); } } private void validatePublic(FrameworkMember member, List errors) { if (!member.isPublic()) { addError(errors, member, "must be public."); } } private void validateTestRuleOrMethodRule(FrameworkMember member, List errors) { if (!isMethodRule(member) && !isTestRule(member)) { addError(errors, member, fMethods ? "must return an implementation of MethodRule or TestRule." : "must implement MethodRule or TestRule."); } } private boolean isTestRule(FrameworkMember member) { return TestRule.class.isAssignableFrom(member.getType()); } @SuppressWarnings("deprecation") private boolean isMethodRule(FrameworkMember member) { return MethodRule.class.isAssignableFrom(member.getType()); } private void addError(List errors, FrameworkMember member, String suffix) { String message = "The @" + fAnnotation.getSimpleName() + " '" + member.getName() + "' " + suffix; errors.add(new Exception(message)); } } junit4-4.11/src/main/java/org/junit/internal/runners/InitializationError.java0000644000175000017500000000133312050524441026731 0ustar ebourgebourgpackage org.junit.internal.runners; import java.util.Arrays; import java.util.List; /** * Use the published version: {@link org.junit.runners.InitializationError} * This may disappear as soon as 1 April 2009 */ @Deprecated public class InitializationError extends Exception { private static final long serialVersionUID = 1L; private final List fErrors; public InitializationError(List errors) { fErrors = errors; } public InitializationError(Throwable... errors) { this(Arrays.asList(errors)); } public InitializationError(String string) { this(new Exception(string)); } public List getCauses() { return fErrors; } } junit4-4.11/src/main/java/org/junit/internal/runners/TestMethod.java0000644000175000017500000000370712050524441025017 0ustar ebourgebourgpackage org.junit.internal.runners; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.Test.None; import org.junit.runners.BlockJUnit4ClassRunner; /** * @deprecated Included for backwards compatibility with JUnit 4.4. Will be * removed in the next release. Please use * {@link BlockJUnit4ClassRunner} in place of {@link JUnit4ClassRunner}. */ @Deprecated public class TestMethod { private final Method fMethod; private TestClass fTestClass; public TestMethod(Method method, TestClass testClass) { fMethod = method; fTestClass = testClass; } public boolean isIgnored() { return fMethod.getAnnotation(Ignore.class) != null; } public long getTimeout() { Test annotation = fMethod.getAnnotation(Test.class); if (annotation == null) { return 0; } long timeout = annotation.timeout(); return timeout; } protected Class getExpectedException() { Test annotation = fMethod.getAnnotation(Test.class); if (annotation == null || annotation.expected() == None.class) { return null; } else { return annotation.expected(); } } boolean isUnexpected(Throwable exception) { return !getExpectedException().isAssignableFrom(exception.getClass()); } boolean expectsException() { return getExpectedException() != null; } List getBefores() { return fTestClass.getAnnotatedMethods(Before.class); } List getAfters() { return fTestClass.getAnnotatedMethods(After.class); } public void invoke(Object test) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { fMethod.invoke(test); } } junit4-4.11/src/main/java/org/junit/internal/runners/JUnit4ClassRunner.java0000644000175000017500000001146212050524441026231 0ustar ebourgebourgpackage org.junit.internal.runners; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import org.junit.runner.Description; import org.junit.runner.Runner; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.Filterable; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runner.manipulation.Sortable; import org.junit.runner.manipulation.Sorter; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; /** * @deprecated Included for backwards compatibility with JUnit 4.4. Will be * removed in the next release. Please use * {@link BlockJUnit4ClassRunner} in place of {@link JUnit4ClassRunner}. * * This may disappear as soon as 1 April 2009 */ @Deprecated public class JUnit4ClassRunner extends Runner implements Filterable, Sortable { private final List fTestMethods; private TestClass fTestClass; public JUnit4ClassRunner(Class klass) throws InitializationError { fTestClass = new TestClass(klass); fTestMethods = getTestMethods(); validate(); } protected List getTestMethods() { return fTestClass.getTestMethods(); } protected void validate() throws InitializationError { MethodValidator methodValidator = new MethodValidator(fTestClass); methodValidator.validateMethodsForDefaultRunner(); methodValidator.assertValid(); } @Override public void run(final RunNotifier notifier) { new ClassRoadie(notifier, fTestClass, getDescription(), new Runnable() { public void run() { runMethods(notifier); } }).runProtected(); } protected void runMethods(final RunNotifier notifier) { for (Method method : fTestMethods) { invokeTestMethod(method, notifier); } } @Override public Description getDescription() { Description spec = Description.createSuiteDescription(getName(), classAnnotations()); List testMethods = fTestMethods; for (Method method : testMethods) { spec.addChild(methodDescription(method)); } return spec; } protected Annotation[] classAnnotations() { return fTestClass.getJavaClass().getAnnotations(); } protected String getName() { return getTestClass().getName(); } protected Object createTest() throws Exception { return getTestClass().getConstructor().newInstance(); } protected void invokeTestMethod(Method method, RunNotifier notifier) { Description description = methodDescription(method); Object test; try { test = createTest(); } catch (InvocationTargetException e) { testAborted(notifier, description, e.getCause()); return; } catch (Exception e) { testAborted(notifier, description, e); return; } TestMethod testMethod = wrapMethod(method); new MethodRoadie(test, testMethod, notifier, description).run(); } private void testAborted(RunNotifier notifier, Description description, Throwable e) { notifier.fireTestStarted(description); notifier.fireTestFailure(new Failure(description, e)); notifier.fireTestFinished(description); } protected TestMethod wrapMethod(Method method) { return new TestMethod(method, fTestClass); } protected String testName(Method method) { return method.getName(); } protected Description methodDescription(Method method) { return Description.createTestDescription(getTestClass().getJavaClass(), testName(method), testAnnotations(method)); } protected Annotation[] testAnnotations(Method method) { return method.getAnnotations(); } public void filter(Filter filter) throws NoTestsRemainException { for (Iterator iter = fTestMethods.iterator(); iter.hasNext(); ) { Method method = iter.next(); if (!filter.shouldRun(methodDescription(method))) { iter.remove(); } } if (fTestMethods.isEmpty()) { throw new NoTestsRemainException(); } } public void sort(final Sorter sorter) { Collections.sort(fTestMethods, new Comparator() { public int compare(Method o1, Method o2) { return sorter.compare(methodDescription(o1), methodDescription(o2)); } }); } protected TestClass getTestClass() { return fTestClass; } }junit4-4.11/src/main/java/org/junit/internal/runners/model/0000755000175000017500000000000012050524441023165 5ustar ebourgebourgjunit4-4.11/src/main/java/org/junit/internal/runners/model/EachTestNotifier.java0000644000175000017500000000274312050524441027236 0ustar ebourgebourgpackage org.junit.internal.runners.model; import org.junit.internal.AssumptionViolatedException; import org.junit.runner.Description; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunNotifier; import org.junit.runners.model.MultipleFailureException; public class EachTestNotifier { private final RunNotifier fNotifier; private final Description fDescription; public EachTestNotifier(RunNotifier notifier, Description description) { fNotifier = notifier; fDescription = description; } public void addFailure(Throwable targetException) { if (targetException instanceof MultipleFailureException) { addMultipleFailureException((MultipleFailureException) targetException); } else { fNotifier .fireTestFailure(new Failure(fDescription, targetException)); } } private void addMultipleFailureException(MultipleFailureException mfe) { for (Throwable each : mfe.getFailures()) { addFailure(each); } } public void addFailedAssumption(AssumptionViolatedException e) { fNotifier.fireTestAssumptionFailed(new Failure(fDescription, e)); } public void fireTestFinished() { fNotifier.fireTestFinished(fDescription); } public void fireTestStarted() { fNotifier.fireTestStarted(fDescription); } public void fireTestIgnored() { fNotifier.fireTestIgnored(fDescription); } }junit4-4.11/src/main/java/org/junit/internal/runners/model/ReflectiveCallable.java0000644000175000017500000000104112050524441027534 0ustar ebourgebourgpackage org.junit.internal.runners.model; import java.lang.reflect.InvocationTargetException; /** * When invoked, throws the exception from the reflected method, rather than * wrapping it in an InvocationTargetException. */ public abstract class ReflectiveCallable { public Object run() throws Throwable { try { return runReflectiveCall(); } catch (InvocationTargetException e) { throw e.getTargetException(); } } protected abstract Object runReflectiveCall() throws Throwable; }junit4-4.11/src/main/java/org/junit/internal/runners/model/MultipleFailureException.java0000644000175000017500000000050312050524441031010 0ustar ebourgebourgpackage org.junit.internal.runners.model; import java.util.List; @Deprecated public class MultipleFailureException extends org.junit.runners.model.MultipleFailureException { private static final long serialVersionUID = 1L; public MultipleFailureException(List errors) { super(errors); } } junit4-4.11/src/main/java/org/junit/internal/runners/statements/0000755000175000017500000000000012050524441024254 5ustar ebourgebourgjunit4-4.11/src/main/java/org/junit/internal/runners/statements/Fail.java0000644000175000017500000000047212050524441025775 0ustar ebourgebourgpackage org.junit.internal.runners.statements; import org.junit.runners.model.Statement; public class Fail extends Statement { private final Throwable fError; public Fail(Throwable e) { fError = e; } @Override public void evaluate() throws Throwable { throw fError; } } junit4-4.11/src/main/java/org/junit/internal/runners/statements/FailOnTimeout.java0000644000175000017500000000472612050524441027647 0ustar ebourgebourgpackage org.junit.internal.runners.statements; import org.junit.runners.model.Statement; public class FailOnTimeout extends Statement { private final Statement fOriginalStatement; private final long fTimeout; public FailOnTimeout(Statement originalStatement, long timeout) { fOriginalStatement = originalStatement; fTimeout = timeout; } @Override public void evaluate() throws Throwable { StatementThread thread = evaluateStatement(); if (!thread.fFinished) { throwExceptionForUnfinishedThread(thread); } } private StatementThread evaluateStatement() throws InterruptedException { StatementThread thread = new StatementThread(fOriginalStatement); thread.start(); thread.join(fTimeout); if (!thread.fFinished) { thread.recordStackTrace(); } thread.interrupt(); return thread; } private void throwExceptionForUnfinishedThread(StatementThread thread) throws Throwable { if (thread.fExceptionThrownByOriginalStatement != null) { throw thread.fExceptionThrownByOriginalStatement; } else { throwTimeoutException(thread); } } private void throwTimeoutException(StatementThread thread) throws Exception { Exception exception = new Exception(String.format( "test timed out after %d milliseconds", fTimeout)); exception.setStackTrace(thread.getRecordedStackTrace()); throw exception; } private static class StatementThread extends Thread { private final Statement fStatement; private boolean fFinished = false; private Throwable fExceptionThrownByOriginalStatement = null; private StackTraceElement[] fRecordedStackTrace = null; public StatementThread(Statement statement) { fStatement = statement; } public void recordStackTrace() { fRecordedStackTrace = getStackTrace(); } public StackTraceElement[] getRecordedStackTrace() { return fRecordedStackTrace; } @Override public void run() { try { fStatement.evaluate(); fFinished = true; } catch (InterruptedException e) { // don't log the InterruptedException } catch (Throwable e) { fExceptionThrownByOriginalStatement = e; } } } }junit4-4.11/src/main/java/org/junit/internal/runners/statements/ExpectException.java0000644000175000017500000000220312050524441030223 0ustar ebourgebourgpackage org.junit.internal.runners.statements; import org.junit.internal.AssumptionViolatedException; import org.junit.runners.model.Statement; public class ExpectException extends Statement { private Statement fNext; private final Class fExpected; public ExpectException(Statement next, Class expected) { fNext = next; fExpected = expected; } @Override public void evaluate() throws Exception { boolean complete = false; try { fNext.evaluate(); complete = true; } catch (AssumptionViolatedException e) { throw e; } catch (Throwable e) { if (!fExpected.isAssignableFrom(e.getClass())) { String message = "Unexpected exception, expected<" + fExpected.getName() + "> but was<" + e.getClass().getName() + ">"; throw new Exception(message, e); } } if (complete) { throw new AssertionError("Expected exception: " + fExpected.getName()); } } }junit4-4.11/src/main/java/org/junit/internal/runners/statements/RunBefores.java0000644000175000017500000000127212050524441027173 0ustar ebourgebourgpackage org.junit.internal.runners.statements; import java.util.List; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; public class RunBefores extends Statement { private final Statement fNext; private final Object fTarget; private final List fBefores; public RunBefores(Statement next, List befores, Object target) { fNext = next; fBefores = befores; fTarget = target; } @Override public void evaluate() throws Throwable { for (FrameworkMethod before : fBefores) { before.invokeExplosively(fTarget); } fNext.evaluate(); } }junit4-4.11/src/main/java/org/junit/internal/runners/statements/InvokeMethod.java0000644000175000017500000000100012050524441027502 0ustar ebourgebourgpackage org.junit.internal.runners.statements; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; public class InvokeMethod extends Statement { private final FrameworkMethod fTestMethod; private Object fTarget; public InvokeMethod(FrameworkMethod testMethod, Object target) { fTestMethod = testMethod; fTarget = target; } @Override public void evaluate() throws Throwable { fTestMethod.invokeExplosively(fTarget); } }junit4-4.11/src/main/java/org/junit/internal/runners/statements/RunAfters.java0000644000175000017500000000214512050524441027032 0ustar ebourgebourgpackage org.junit.internal.runners.statements; import java.util.ArrayList; import java.util.List; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.MultipleFailureException; import org.junit.runners.model.Statement; public class RunAfters extends Statement { private final Statement fNext; private final Object fTarget; private final List fAfters; public RunAfters(Statement next, List afters, Object target) { fNext = next; fAfters = afters; fTarget = target; } @Override public void evaluate() throws Throwable { List errors = new ArrayList(); try { fNext.evaluate(); } catch (Throwable e) { errors.add(e); } finally { for (FrameworkMethod each : fAfters) { try { each.invokeExplosively(fTarget); } catch (Throwable e) { errors.add(e); } } } MultipleFailureException.assertEmpty(errors); } }junit4-4.11/src/main/java/org/junit/internal/runners/JUnit38ClassRunner.java0000644000175000017500000001256012050524441026320 0ustar ebourgebourgpackage org.junit.internal.runners; import junit.extensions.TestDecorator; import junit.framework.AssertionFailedError; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestListener; import junit.framework.TestResult; import junit.framework.TestSuite; import org.junit.runner.Describable; import org.junit.runner.Description; import org.junit.runner.Runner; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.Filterable; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runner.manipulation.Sortable; import org.junit.runner.manipulation.Sorter; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunNotifier; public class JUnit38ClassRunner extends Runner implements Filterable, Sortable { private final class OldTestClassAdaptingListener implements TestListener { private final RunNotifier fNotifier; private OldTestClassAdaptingListener(RunNotifier notifier) { fNotifier = notifier; } public void endTest(Test test) { fNotifier.fireTestFinished(asDescription(test)); } public void startTest(Test test) { fNotifier.fireTestStarted(asDescription(test)); } // Implement junit.framework.TestListener public void addError(Test test, Throwable t) { Failure failure = new Failure(asDescription(test), t); fNotifier.fireTestFailure(failure); } private Description asDescription(Test test) { if (test instanceof Describable) { Describable facade = (Describable) test; return facade.getDescription(); } return Description.createTestDescription(getEffectiveClass(test), getName(test)); } private Class getEffectiveClass(Test test) { return test.getClass(); } private String getName(Test test) { if (test instanceof TestCase) { return ((TestCase) test).getName(); } else { return test.toString(); } } public void addFailure(Test test, AssertionFailedError t) { addError(test, t); } } private Test fTest; public JUnit38ClassRunner(Class klass) { this(new TestSuite(klass.asSubclass(TestCase.class))); } public JUnit38ClassRunner(Test test) { super(); setTest(test); } @Override public void run(RunNotifier notifier) { TestResult result = new TestResult(); result.addListener(createAdaptingListener(notifier)); getTest().run(result); } public TestListener createAdaptingListener(final RunNotifier notifier) { return new OldTestClassAdaptingListener(notifier); } @Override public Description getDescription() { return makeDescription(getTest()); } private static Description makeDescription(Test test) { if (test instanceof TestCase) { TestCase tc = (TestCase) test; return Description.createTestDescription(tc.getClass(), tc.getName()); } else if (test instanceof TestSuite) { TestSuite ts = (TestSuite) test; String name = ts.getName() == null ? createSuiteDescription(ts) : ts.getName(); Description description = Description.createSuiteDescription(name); int n = ts.testCount(); for (int i = 0; i < n; i++) { Description made = makeDescription(ts.testAt(i)); description.addChild(made); } return description; } else if (test instanceof Describable) { Describable adapter = (Describable) test; return adapter.getDescription(); } else if (test instanceof TestDecorator) { TestDecorator decorator = (TestDecorator) test; return makeDescription(decorator.getTest()); } else { // This is the best we can do in this case return Description.createSuiteDescription(test.getClass()); } } private static String createSuiteDescription(TestSuite ts) { int count = ts.countTestCases(); String example = count == 0 ? "" : String.format(" [example: %s]", ts.testAt(0)); return String.format("TestSuite with %s tests%s", count, example); } public void filter(Filter filter) throws NoTestsRemainException { if (getTest() instanceof Filterable) { Filterable adapter = (Filterable) getTest(); adapter.filter(filter); } else if (getTest() instanceof TestSuite) { TestSuite suite = (TestSuite) getTest(); TestSuite filtered = new TestSuite(suite.getName()); int n = suite.testCount(); for (int i = 0; i < n; i++) { Test test = suite.testAt(i); if (filter.shouldRun(makeDescription(test))) { filtered.addTest(test); } } setTest(filtered); } } public void sort(Sorter sorter) { if (getTest() instanceof Sortable) { Sortable adapter = (Sortable) getTest(); adapter.sort(sorter); } } private void setTest(Test test) { fTest = test; } private Test getTest() { return fTest; } } junit4-4.11/src/main/java/org/junit/internal/runners/TestClass.java0000644000175000017500000000640312050524441024640 0ustar ebourgebourgpackage org.junit.internal.runners; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.internal.MethodSorter; import org.junit.runners.BlockJUnit4ClassRunner; /** * @deprecated Included for backwards compatibility with JUnit 4.4. Will be * removed in the next release. Please use * {@link BlockJUnit4ClassRunner} in place of {@link JUnit4ClassRunner}. */ @Deprecated public class TestClass { private final Class fClass; public TestClass(Class klass) { fClass = klass; } public List getTestMethods() { return getAnnotatedMethods(Test.class); } List getBefores() { return getAnnotatedMethods(BeforeClass.class); } List getAfters() { return getAnnotatedMethods(AfterClass.class); } public List getAnnotatedMethods(Class annotationClass) { List results = new ArrayList(); for (Class eachClass : getSuperClasses(fClass)) { Method[] methods = MethodSorter.getDeclaredMethods(eachClass); for (Method eachMethod : methods) { Annotation annotation = eachMethod.getAnnotation(annotationClass); if (annotation != null && !isShadowed(eachMethod, results)) { results.add(eachMethod); } } } if (runsTopToBottom(annotationClass)) { Collections.reverse(results); } return results; } private boolean runsTopToBottom(Class annotation) { return annotation.equals(Before.class) || annotation.equals(BeforeClass.class); } private boolean isShadowed(Method method, List results) { for (Method each : results) { if (isShadowed(method, each)) { return true; } } return false; } private boolean isShadowed(Method current, Method previous) { if (!previous.getName().equals(current.getName())) { return false; } if (previous.getParameterTypes().length != current.getParameterTypes().length) { return false; } for (int i = 0; i < previous.getParameterTypes().length; i++) { if (!previous.getParameterTypes()[i].equals(current.getParameterTypes()[i])) { return false; } } return true; } private List> getSuperClasses(Class testClass) { ArrayList> results = new ArrayList>(); Class current = testClass; while (current != null) { results.add(current); current = current.getSuperclass(); } return results; } public Constructor getConstructor() throws SecurityException, NoSuchMethodException { return fClass.getConstructor(); } public Class getJavaClass() { return fClass; } public String getName() { return fClass.getName(); } } junit4-4.11/src/main/java/org/junit/internal/runners/FailedBefore.java0000644000175000017500000000064012050524441025237 0ustar ebourgebourgpackage org.junit.internal.runners; import org.junit.runners.BlockJUnit4ClassRunner; /** * @deprecated Included for backwards compatibility with JUnit 4.4. Will be * removed in the next release. Please use * {@link BlockJUnit4ClassRunner} in place of {@link JUnit4ClassRunner}. */ @Deprecated class FailedBefore extends Exception { private static final long serialVersionUID = 1L; }junit4-4.11/src/main/java/org/junit/internal/runners/ClassRoadie.java0000644000175000017500000000456412050524441025132 0ustar ebourgebourgpackage org.junit.internal.runners; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import org.junit.runner.Description; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; /** * @deprecated Included for backwards compatibility with JUnit 4.4. Will be * removed in the next release. Please use * {@link BlockJUnit4ClassRunner} in place of {@link JUnit4ClassRunner}. */ @Deprecated public class ClassRoadie { private RunNotifier fNotifier; private TestClass fTestClass; private Description fDescription; private final Runnable fRunnable; public ClassRoadie(RunNotifier notifier, TestClass testClass, Description description, Runnable runnable) { fNotifier = notifier; fTestClass = testClass; fDescription = description; fRunnable = runnable; } protected void runUnprotected() { fRunnable.run(); } ; protected void addFailure(Throwable targetException) { fNotifier.fireTestFailure(new Failure(fDescription, targetException)); } public void runProtected() { try { runBefores(); runUnprotected(); } catch (FailedBefore e) { } finally { runAfters(); } } private void runBefores() throws FailedBefore { try { try { List befores = fTestClass.getBefores(); for (Method before : befores) { before.invoke(null); } } catch (InvocationTargetException e) { throw e.getTargetException(); } } catch (org.junit.internal.AssumptionViolatedException e) { throw new FailedBefore(); } catch (Throwable e) { addFailure(e); throw new FailedBefore(); } } private void runAfters() { List afters = fTestClass.getAfters(); for (Method after : afters) { try { after.invoke(null); } catch (InvocationTargetException e) { addFailure(e.getTargetException()); } catch (Throwable e) { addFailure(e); // Untested, but seems impossible } } } }junit4-4.11/src/main/java/org/junit/internal/runners/MethodRoadie.java0000644000175000017500000001272012050524441025276 0ustar ebourgebourgpackage org.junit.internal.runners; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.junit.internal.AssumptionViolatedException; import org.junit.runner.Description; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; /** * @deprecated Included for backwards compatibility with JUnit 4.4. Will be * removed in the next release. Please use * {@link BlockJUnit4ClassRunner} in place of {@link JUnit4ClassRunner}. */ @Deprecated public class MethodRoadie { private final Object fTest; private final RunNotifier fNotifier; private final Description fDescription; private TestMethod fTestMethod; public MethodRoadie(Object test, TestMethod method, RunNotifier notifier, Description description) { fTest = test; fNotifier = notifier; fDescription = description; fTestMethod = method; } public void run() { if (fTestMethod.isIgnored()) { fNotifier.fireTestIgnored(fDescription); return; } fNotifier.fireTestStarted(fDescription); try { long timeout = fTestMethod.getTimeout(); if (timeout > 0) { runWithTimeout(timeout); } else { runTest(); } } finally { fNotifier.fireTestFinished(fDescription); } } private void runWithTimeout(final long timeout) { runBeforesThenTestThenAfters(new Runnable() { public void run() { ExecutorService service = Executors.newSingleThreadExecutor(); Callable callable = new Callable() { public Object call() throws Exception { runTestMethod(); return null; } }; Future result = service.submit(callable); service.shutdown(); try { boolean terminated = service.awaitTermination(timeout, TimeUnit.MILLISECONDS); if (!terminated) { service.shutdownNow(); } result.get(0, TimeUnit.MILLISECONDS); // throws the exception if one occurred during the invocation } catch (TimeoutException e) { addFailure(new Exception(String.format("test timed out after %d milliseconds", timeout))); } catch (Exception e) { addFailure(e); } } }); } public void runTest() { runBeforesThenTestThenAfters(new Runnable() { public void run() { runTestMethod(); } }); } public void runBeforesThenTestThenAfters(Runnable test) { try { runBefores(); test.run(); } catch (FailedBefore e) { } catch (Exception e) { throw new RuntimeException("test should never throw an exception to this level"); } finally { runAfters(); } } protected void runTestMethod() { try { fTestMethod.invoke(fTest); if (fTestMethod.expectsException()) { addFailure(new AssertionError("Expected exception: " + fTestMethod.getExpectedException().getName())); } } catch (InvocationTargetException e) { Throwable actual = e.getTargetException(); if (actual instanceof AssumptionViolatedException) { return; } else if (!fTestMethod.expectsException()) { addFailure(actual); } else if (fTestMethod.isUnexpected(actual)) { String message = "Unexpected exception, expected<" + fTestMethod.getExpectedException().getName() + "> but was<" + actual.getClass().getName() + ">"; addFailure(new Exception(message, actual)); } } catch (Throwable e) { addFailure(e); } } private void runBefores() throws FailedBefore { try { try { List befores = fTestMethod.getBefores(); for (Method before : befores) { before.invoke(fTest); } } catch (InvocationTargetException e) { throw e.getTargetException(); } } catch (AssumptionViolatedException e) { throw new FailedBefore(); } catch (Throwable e) { addFailure(e); throw new FailedBefore(); } } private void runAfters() { List afters = fTestMethod.getAfters(); for (Method after : afters) { try { after.invoke(fTest); } catch (InvocationTargetException e) { addFailure(e.getTargetException()); } catch (Throwable e) { addFailure(e); // Untested, but seems impossible } } } protected void addFailure(Throwable e) { fNotifier.fireTestFailure(new Failure(fDescription, e)); } } junit4-4.11/src/main/java/org/junit/internal/runners/ErrorReportingRunner.java0000644000175000017500000000407012050524441027106 0ustar ebourgebourgpackage org.junit.internal.runners; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.List; import org.junit.runner.Description; import org.junit.runner.Runner; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunNotifier; import org.junit.runners.model.InitializationError; public class ErrorReportingRunner extends Runner { private final List fCauses; private final Class fTestClass; public ErrorReportingRunner(Class testClass, Throwable cause) { fTestClass = testClass; fCauses = getCauses(cause); } @Override public Description getDescription() { Description description = Description.createSuiteDescription(fTestClass); for (Throwable each : fCauses) { description.addChild(describeCause(each)); } return description; } @Override public void run(RunNotifier notifier) { for (Throwable each : fCauses) { runCause(each, notifier); } } @SuppressWarnings("deprecation") private List getCauses(Throwable cause) { if (cause instanceof InvocationTargetException) { return getCauses(cause.getCause()); } if (cause instanceof InitializationError) { return ((InitializationError) cause).getCauses(); } if (cause instanceof org.junit.internal.runners.InitializationError) { return ((org.junit.internal.runners.InitializationError) cause) .getCauses(); } return Arrays.asList(cause); } private Description describeCause(Throwable child) { return Description.createTestDescription(fTestClass, "initializationError"); } private void runCause(Throwable child, RunNotifier notifier) { Description description = describeCause(child); notifier.fireTestStarted(description); notifier.fireTestFailure(new Failure(description, child)); notifier.fireTestFinished(description); } }junit4-4.11/src/main/java/org/junit/internal/runners/SuiteMethod.java0000644000175000017500000000230312050524441025160 0ustar ebourgebourgpackage org.junit.internal.runners; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import junit.framework.Test; /** * Runner for use with JUnit 3.8.x-style AllTests classes * (those that only implement a static suite() * method). For example: *
     * @RunWith(AllTests.class)
     * public class ProductTests {
     *    public static junit.framework.Test suite() {
     *       ...
     *    }
     * }
     * 
    */ public class SuiteMethod extends JUnit38ClassRunner { public SuiteMethod(Class klass) throws Throwable { super(testFromSuiteMethod(klass)); } public static Test testFromSuiteMethod(Class klass) throws Throwable { Method suiteMethod = null; Test suite = null; try { suiteMethod = klass.getMethod("suite"); if (!Modifier.isStatic(suiteMethod.getModifiers())) { throw new Exception(klass.getName() + ".suite() must be static"); } suite = (Test) suiteMethod.invoke(null); // static method } catch (InvocationTargetException e) { throw e.getCause(); } return suite; } } junit4-4.11/src/main/java/org/junit/internal/ArrayComparisonFailure.java0000644000175000017500000000331212050524441025654 0ustar ebourgebourgpackage org.junit.internal; import java.util.ArrayList; import java.util.List; import org.junit.Assert; /** * Thrown when two array elements differ * * @see Assert#assertArrayEquals(String, Object[], Object[]) */ public class ArrayComparisonFailure extends AssertionError { private static final long serialVersionUID = 1L; private List fIndices = new ArrayList(); private final String fMessage; private final AssertionError fCause; /** * Construct a new ArrayComparisonFailure with an error text and the array's * dimension that was not equal * * @param cause the exception that caused the array's content to fail the assertion test * @param index the array position of the objects that are not equal. * @see Assert#assertArrayEquals(String, Object[], Object[]) */ public ArrayComparisonFailure(String message, AssertionError cause, int index) { fMessage = message; fCause = cause; addDimension(index); } public void addDimension(int index) { fIndices.add(0, index); } @Override public String getMessage() { StringBuilder builder = new StringBuilder(); if (fMessage != null) { builder.append(fMessage); } builder.append("arrays first differed at element "); for (int each : fIndices) { builder.append("["); builder.append(each); builder.append("]"); } builder.append("; "); builder.append(fCause.getMessage()); return builder.toString(); } /** * {@inheritDoc} */ @Override public String toString() { return getMessage(); } } junit4-4.11/src/main/java/org/junit/internal/JUnitSystem.java0000644000175000017500000000016212050524441023471 0ustar ebourgebourgpackage org.junit.internal; import java.io.PrintStream; public interface JUnitSystem { PrintStream out(); } junit4-4.11/src/main/java/org/junit/internal/AssumptionViolatedException.java0000644000175000017500000000513312050524441026747 0ustar ebourgebourgpackage org.junit.internal; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.SelfDescribing; import org.hamcrest.StringDescription; /** * An exception class used to implement assumptions (state in which a given test * is meaningful and should or should not be executed). A test for which an assumption * fails should not generate a test case failure. * * @see Assume */ public class AssumptionViolatedException extends RuntimeException implements SelfDescribing { private static final long serialVersionUID = 2L; private final String fAssumption; private final boolean fValueMatcher; private final Object fValue; private final Matcher fMatcher; public AssumptionViolatedException(String assumption, boolean valueMatcher, Object value, Matcher matcher) { super(value instanceof Throwable ? (Throwable) value : null); fAssumption = assumption; fValue = value; fMatcher = matcher; fValueMatcher = valueMatcher; } /** * An assumption exception with the given value (String or * Throwable) and an additional failing {@link Matcher}. */ public AssumptionViolatedException(Object value, Matcher matcher) { this(null, true, value, matcher); } /** * An assumption exception with the given value (String or * Throwable) and an additional failing {@link Matcher}. */ public AssumptionViolatedException(String assumption, Object value, Matcher matcher) { this(assumption, true, value, matcher); } /** * An assumption exception with the given message only. */ public AssumptionViolatedException(String assumption) { this(assumption, false, null, null); } /** * An assumption exception with the given message and a cause. */ public AssumptionViolatedException(String assumption, Throwable t) { this(assumption, false, t, null); } @Override public String getMessage() { return StringDescription.asString(this); } public void describeTo(Description description) { if (fAssumption != null) { description.appendText(fAssumption); } if (fValueMatcher) { if (fAssumption != null) { description.appendText(": "); } description.appendText("got: "); description.appendValue(fValue); if (fMatcher != null) { description.appendText(", expected: "); description.appendDescriptionOf(fMatcher); } } } }junit4-4.11/src/main/java/org/junit/internal/RealSystem.java0000644000175000017500000000025612050524441023327 0ustar ebourgebourgpackage org.junit.internal; import java.io.PrintStream; public class RealSystem implements JUnitSystem { public PrintStream out() { return System.out; } } junit4-4.11/src/main/java/org/junit/runner/0000755000175000017500000000000012050524441020066 5ustar ebourgebourgjunit4-4.11/src/main/java/org/junit/runner/JUnitCore.java0000644000175000017500000001505512050524441022601 0ustar ebourgebourgpackage org.junit.runner; import java.util.ArrayList; import java.util.List; import junit.runner.Version; import org.junit.internal.JUnitSystem; import org.junit.internal.RealSystem; import org.junit.internal.TextListener; import org.junit.internal.runners.JUnit38ClassRunner; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; import org.junit.runner.notification.RunNotifier; /** * JUnitCore is a facade for running tests. It supports running JUnit 4 tests, * JUnit 3.8.x tests, and mixtures. To run tests from the command line, run * java org.junit.runner.JUnitCore TestClass1 TestClass2 .... * For one-shot test runs, use the static method {@link #runClasses(Class[])}. * If you want to add special listeners, * create an instance of {@link org.junit.runner.JUnitCore} first and use it to run the tests. * * @see org.junit.runner.Result * @see org.junit.runner.notification.RunListener * @see org.junit.runner.Request * @since 4.0 */ public class JUnitCore { private final RunNotifier fNotifier = new RunNotifier(); /** * Run the tests contained in the classes named in the args. * If all tests run successfully, exit with a status of 0. Otherwise exit with a status of 1. * Write feedback while tests are running and write * stack traces for all failed tests after the tests all complete. * * @param args names of classes in which to find tests to run */ public static void main(String... args) { runMainAndExit(new RealSystem(), args); } /** * Runs main and exits */ private static void runMainAndExit(JUnitSystem system, String... args) { Result result = new JUnitCore().runMain(system, args); System.exit(result.wasSuccessful() ? 0 : 1); } /** * Run the tests contained in classes. Write feedback while the tests * are running and write stack traces for all failed tests after all tests complete. This is * similar to {@link #main(String[])}, but intended to be used programmatically. * * @param computer Helps construct Runners from classes * @param classes Classes in which to find tests * @return a {@link Result} describing the details of the test run and the failed tests. */ public static Result runClasses(Computer computer, Class... classes) { return new JUnitCore().run(computer, classes); } /** * Run the tests contained in classes. Write feedback while the tests * are running and write stack traces for all failed tests after all tests complete. This is * similar to {@link #main(String[])}, but intended to be used programmatically. * * @param classes Classes in which to find tests * @return a {@link Result} describing the details of the test run and the failed tests. */ public static Result runClasses(Class... classes) { return new JUnitCore().run(defaultComputer(), classes); } /** * @param system * @args args from main() */ private Result runMain(JUnitSystem system, String... args) { system.out().println("JUnit version " + Version.id()); List> classes = new ArrayList>(); List missingClasses = new ArrayList(); for (String each : args) { try { classes.add(Class.forName(each)); } catch (ClassNotFoundException e) { system.out().println("Could not find class: " + each); Description description = Description.createSuiteDescription(each); Failure failure = new Failure(description, e); missingClasses.add(failure); } } RunListener listener = new TextListener(system); addListener(listener); Result result = run(classes.toArray(new Class[0])); for (Failure each : missingClasses) { result.getFailures().add(each); } return result; } /** * @return the version number of this release */ public String getVersion() { return Version.id(); } /** * Run all the tests in classes. * * @param classes the classes containing tests * @return a {@link Result} describing the details of the test run and the failed tests. */ public Result run(Class... classes) { return run(Request.classes(defaultComputer(), classes)); } /** * Run all the tests in classes. * * @param computer Helps construct Runners from classes * @param classes the classes containing tests * @return a {@link Result} describing the details of the test run and the failed tests. */ public Result run(Computer computer, Class... classes) { return run(Request.classes(computer, classes)); } /** * Run all the tests contained in request. * * @param request the request describing tests * @return a {@link Result} describing the details of the test run and the failed tests. */ public Result run(Request request) { return run(request.getRunner()); } /** * Run all the tests contained in JUnit 3.8.x test. Here for backward compatibility. * * @param test the old-style test * @return a {@link Result} describing the details of the test run and the failed tests. */ public Result run(junit.framework.Test test) { return run(new JUnit38ClassRunner(test)); } /** * Do not use. Testing purposes only. */ public Result run(Runner runner) { Result result = new Result(); RunListener listener = result.createListener(); fNotifier.addFirstListener(listener); try { fNotifier.fireTestRunStarted(runner.getDescription()); runner.run(fNotifier); fNotifier.fireTestRunFinished(result); } finally { removeListener(listener); } return result; } /** * Add a listener to be notified as the tests run. * * @param listener the listener to add * @see org.junit.runner.notification.RunListener */ public void addListener(RunListener listener) { fNotifier.addListener(listener); } /** * Remove a listener. * * @param listener the listener to remove */ public void removeListener(RunListener listener) { fNotifier.removeListener(listener); } static Computer defaultComputer() { return new Computer(); } } junit4-4.11/src/main/java/org/junit/runner/package-info.java0000644000175000017500000000020112050524441023246 0ustar ebourgebourg/** * Provides classes used to describe, collect, run and analyze multiple tests. * * @since 4.0 */ package org.junit.runner;junit4-4.11/src/main/java/org/junit/runner/Result.java0000644000175000017500000000555012050524441022214 0ustar ebourgebourgpackage org.junit.runner; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; /** * A Result collects and summarizes information from running multiple tests. * All tests are counted -- additional information is collected from tests that fail. * * @since 4.0 */ public class Result implements Serializable { private static final long serialVersionUID = 1L; private AtomicInteger fCount = new AtomicInteger(); private AtomicInteger fIgnoreCount = new AtomicInteger(); private final List fFailures = Collections.synchronizedList(new ArrayList()); private long fRunTime = 0; private long fStartTime; /** * @return the number of tests run */ public int getRunCount() { return fCount.get(); } /** * @return the number of tests that failed during the run */ public int getFailureCount() { return fFailures.size(); } /** * @return the number of milliseconds it took to run the entire suite to run */ public long getRunTime() { return fRunTime; } /** * @return the {@link Failure}s describing tests that failed and the problems they encountered */ public List getFailures() { return fFailures; } /** * @return the number of tests ignored during the run */ public int getIgnoreCount() { return fIgnoreCount.get(); } /** * @return true if all tests succeeded */ public boolean wasSuccessful() { return getFailureCount() == 0; } private class Listener extends RunListener { @Override public void testRunStarted(Description description) throws Exception { fStartTime = System.currentTimeMillis(); } @Override public void testRunFinished(Result result) throws Exception { long endTime = System.currentTimeMillis(); fRunTime += endTime - fStartTime; } @Override public void testFinished(Description description) throws Exception { fCount.getAndIncrement(); } @Override public void testFailure(Failure failure) throws Exception { fFailures.add(failure); } @Override public void testIgnored(Description description) throws Exception { fIgnoreCount.getAndIncrement(); } @Override public void testAssumptionFailure(Failure failure) { // do nothing: same as passing (for 4.5; may change in 4.6) } } /** * Internal use only. */ public RunListener createListener() { return new Listener(); } } junit4-4.11/src/main/java/org/junit/runner/Description.java0000644000175000017500000002624512050524441023225 0ustar ebourgebourgpackage org.junit.runner; import java.io.Serializable; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.regex.Matcher; import java.util.regex.Pattern; /** *

    A Description describes a test which is to be run or has been run. Descriptions * can be atomic (a single test) or compound (containing children tests). Descriptions are used * to provide feedback about the tests that are about to run (for example, the tree view * visible in many IDEs) or tests that have been run (for example, the failures view).

    * *

    Descriptions are implemented as a single class rather than a Composite because * they are entirely informational. They contain no logic aside from counting their tests.

    * *

    In the past, we used the raw {@link junit.framework.TestCase}s and {@link junit.framework.TestSuite}s * to display the tree of tests. This was no longer viable in JUnit 4 because atomic tests no longer have * a superclass below {@link Object}. We needed a way to pass a class and name together. Description * emerged from this.

    * * @see org.junit.runner.Request * @see org.junit.runner.Runner * @since 4.0 */ public class Description implements Serializable { private static final long serialVersionUID = 1L; private static final Pattern METHOD_AND_CLASS_NAME_PATTERN = Pattern .compile("(.*)\\((.*)\\)"); /** * Create a Description named name. * Generally, you will add children to this Description. * * @param name the name of the Description * @param annotations meta-data about the test, for downstream interpreters * @return a Description named name */ public static Description createSuiteDescription(String name, Annotation... annotations) { return new Description(null, name, annotations); } /** * Create a Description named name. * Generally, you will add children to this Description. * * @param name the name of the Description * @param uniqueId an arbitrary object used to define uniqueness (in {@link #equals(Object)} * @param annotations meta-data about the test, for downstream interpreters * @return a Description named name */ public static Description createSuiteDescription(String name, Serializable uniqueId, Annotation... annotations) { return new Description(null, name, uniqueId, annotations); } /** * Create a Description of a single test named name in the 'class' named * className. Generally, this will be a leaf Description. This method is a better choice * than {@link #createTestDescription(Class, String, Annotation...)} for test runners whose test cases are not * defined in an actual Java Class. * * @param className the class name of the test * @param name the name of the test (a method name for test annotated with {@link org.junit.Test}) * @param annotations meta-data about the test, for downstream interpreters * @return a Description named name */ public static Description createTestDescription(String className, String name, Annotation... annotations) { return new Description(null, formatDisplayName(name, className), annotations); } /** * Create a Description of a single test named name in the class clazz. * Generally, this will be a leaf Description. * * @param clazz the class of the test * @param name the name of the test (a method name for test annotated with {@link org.junit.Test}) * @param annotations meta-data about the test, for downstream interpreters * @return a Description named name */ public static Description createTestDescription(Class clazz, String name, Annotation... annotations) { return new Description(clazz, formatDisplayName(name, clazz.getName()), annotations); } /** * Create a Description of a single test named name in the class clazz. * Generally, this will be a leaf Description. * (This remains for binary compatibility with clients of JUnit 4.3) * * @param clazz the class of the test * @param name the name of the test (a method name for test annotated with {@link org.junit.Test}) * @return a Description named name */ public static Description createTestDescription(Class clazz, String name) { return new Description(clazz, formatDisplayName(name, clazz.getName())); } /** * Create a Description of a single test named name in the class clazz. * Generally, this will be a leaf Description. * * @param name the name of the test (a method name for test annotated with {@link org.junit.Test}) * @return a Description named name */ public static Description createTestDescription(String className, String name, Serializable uniqueId) { return new Description(null, formatDisplayName(name, className), uniqueId); } private static String formatDisplayName(String name, String className) { return String.format("%s(%s)", name, className); } /** * Create a Description named after testClass * * @param testClass A {@link Class} containing tests * @return a Description of testClass */ public static Description createSuiteDescription(Class testClass) { return new Description(testClass, testClass.getName(), testClass.getAnnotations()); } /** * Describes a Runner which runs no tests */ public static final Description EMPTY = new Description(null, "No Tests"); /** * Describes a step in the test-running mechanism that goes so wrong no * other description can be used (for example, an exception thrown from a Runner's * constructor */ public static final Description TEST_MECHANISM = new Description(null, "Test mechanism"); private final ArrayList fChildren = new ArrayList(); private final String fDisplayName; private final Serializable fUniqueId; private final Annotation[] fAnnotations; private /* write-once */ Class fTestClass; private Description(Class clazz, String displayName, Annotation... annotations) { this(clazz, displayName, displayName, annotations); } private Description(Class clazz, String displayName, Serializable uniqueId, Annotation... annotations) { if ((displayName == null) || (displayName.length() == 0)) { throw new IllegalArgumentException( "The display name must not be empty."); } if ((uniqueId == null)) { throw new IllegalArgumentException( "The unique id must not be null."); } fTestClass = clazz; fDisplayName = displayName; fUniqueId = uniqueId; fAnnotations = annotations; } /** * @return a user-understandable label */ public String getDisplayName() { return fDisplayName; } /** * Add Description as a child of the receiver. * * @param description the soon-to-be child. */ public void addChild(Description description) { getChildren().add(description); } /** * @return the receiver's children, if any */ public ArrayList getChildren() { return fChildren; } /** * @return true if the receiver is a suite */ public boolean isSuite() { return !isTest(); } /** * @return true if the receiver is an atomic test */ public boolean isTest() { return getChildren().isEmpty(); } /** * @return the total number of atomic tests in the receiver */ public int testCount() { if (isTest()) { return 1; } int result = 0; for (Description child : getChildren()) { result += child.testCount(); } return result; } @Override public int hashCode() { return fUniqueId.hashCode(); } @Override public boolean equals(Object obj) { if (!(obj instanceof Description)) { return false; } Description d = (Description) obj; return fUniqueId.equals(d.fUniqueId); } @Override public String toString() { return getDisplayName(); } /** * @return true if this is a description of a Runner that runs no tests */ public boolean isEmpty() { return equals(EMPTY); } /** * @return a copy of this description, with no children (on the assumption that some of the * children will be added back) */ public Description childlessCopy() { return new Description(fTestClass, fDisplayName, fAnnotations); } /** * @return the annotation of type annotationType that is attached to this description node, * or null if none exists */ public T getAnnotation(Class annotationType) { for (Annotation each : fAnnotations) { if (each.annotationType().equals(annotationType)) { return annotationType.cast(each); } } return null; } /** * @return all of the annotations attached to this description node */ public Collection getAnnotations() { return Arrays.asList(fAnnotations); } /** * @return If this describes a method invocation, * the class of the test instance. */ public Class getTestClass() { if (fTestClass != null) { return fTestClass; } String name = getClassName(); if (name == null) { return null; } try { fTestClass = Class.forName(name, false, getClass().getClassLoader()); return fTestClass; } catch (ClassNotFoundException e) { return null; } } /** * @return If this describes a method invocation, * the name of the class of the test instance */ public String getClassName() { return fTestClass != null ? fTestClass.getName() : methodAndClassNamePatternGroupOrDefault(2, toString()); } /** * @return If this describes a method invocation, * the name of the method (or null if not) */ public String getMethodName() { return methodAndClassNamePatternGroupOrDefault(1, null); } private String methodAndClassNamePatternGroupOrDefault(int group, String defaultString) { Matcher matcher = METHOD_AND_CLASS_NAME_PATTERN.matcher(toString()); return matcher.matches() ? matcher.group(group) : defaultString; } }junit4-4.11/src/main/java/org/junit/runner/manipulation/0000755000175000017500000000000012050524441022566 5ustar ebourgebourgjunit4-4.11/src/main/java/org/junit/runner/manipulation/Filter.java0000644000175000017500000000754412050524441024670 0ustar ebourgebourgpackage org.junit.runner.manipulation; import org.junit.runner.Description; import org.junit.runner.Request; /** * The canonical case of filtering is when you want to run a single test method in a class. Rather * than introduce runner API just for that one case, JUnit provides a general filtering mechanism. * If you want to filter the tests to be run, extend Filter and apply an instance of * your filter to the {@link org.junit.runner.Request} before running it (see * {@link org.junit.runner.JUnitCore#run(Request)}. Alternatively, apply a Filter to * a {@link org.junit.runner.Runner} before running tests (for example, in conjunction with * {@link org.junit.runner.RunWith}. * * @since 4.0 */ public abstract class Filter { /** * A null Filter that passes all tests through. */ public static Filter ALL = new Filter() { @Override public boolean shouldRun(Description description) { return true; } @Override public String describe() { return "all tests"; } @Override public void apply(Object child) throws NoTestsRemainException { // do nothing } @Override public Filter intersect(Filter second) { return second; } }; /** * Returns a {@code Filter} that only runs the single method described by * {@code desiredDescription} */ public static Filter matchMethodDescription(final Description desiredDescription) { return new Filter() { @Override public boolean shouldRun(Description description) { if (description.isTest()) { return desiredDescription.equals(description); } // explicitly check if any children want to run for (Description each : description.getChildren()) { if (shouldRun(each)) { return true; } } return false; } @Override public String describe() { return String.format("Method %s", desiredDescription.getDisplayName()); } }; } /** * @param description the description of the test to be run * @return true if the test should be run */ public abstract boolean shouldRun(Description description); /** * Returns a textual description of this Filter * * @return a textual description of this Filter */ public abstract String describe(); /** * Invoke with a {@link org.junit.runner.Runner} to cause all tests it intends to run * to first be checked with the filter. Only those that pass the filter will be run. * * @param child the runner to be filtered by the receiver * @throws NoTestsRemainException if the receiver removes all tests */ public void apply(Object child) throws NoTestsRemainException { if (!(child instanceof Filterable)) { return; } Filterable filterable = (Filterable) child; filterable.filter(this); } /** * Returns a new Filter that accepts the intersection of the tests accepted * by this Filter and {@code second} */ public Filter intersect(final Filter second) { if (second == this || second == ALL) { return this; } final Filter first = this; return new Filter() { @Override public boolean shouldRun(Description description) { return first.shouldRun(description) && second.shouldRun(description); } @Override public String describe() { return first.describe() + " and " + second.describe(); } }; } } junit4-4.11/src/main/java/org/junit/runner/manipulation/package-info.java0000644000175000017500000000034612050524441025760 0ustar ebourgebourg/** * Provides classes to {@link org.junit.runner.manipulation.Filter filter} or {@link org.junit.runner.manipulation.Sorter sort} tests. * * @since 4.0 * @see org.junit.runner.Runner */ package org.junit.runner.manipulation;junit4-4.11/src/main/java/org/junit/runner/manipulation/NoTestsRemainException.java0000644000175000017500000000035112050524441030042 0ustar ebourgebourgpackage org.junit.runner.manipulation; /** * Thrown when a filter removes all tests from a runner. * * @since 4.0 */ public class NoTestsRemainException extends Exception { private static final long serialVersionUID = 1L; } junit4-4.11/src/main/java/org/junit/runner/manipulation/Filterable.java0000644000175000017500000000100612050524441025477 0ustar ebourgebourgpackage org.junit.runner.manipulation; /** * Runners that allow filtering should implement this interface. Implement {@link #filter(Filter)} * to remove tests that don't pass the filter. * * @since 4.0 */ public interface Filterable { /** * Remove tests that don't pass the parameter filter. * * @param filter the {@link Filter} to apply * @throws NoTestsRemainException if all tests are filtered out */ void filter(Filter filter) throws NoTestsRemainException; } junit4-4.11/src/main/java/org/junit/runner/manipulation/Sorter.java0000644000175000017500000000252412050524441024712 0ustar ebourgebourgpackage org.junit.runner.manipulation; import java.util.Comparator; import org.junit.runner.Description; /** * A Sorter orders tests. In general you will not need * to use a Sorter directly. Instead, use {@link org.junit.runner.Request#sortWith(Comparator)}. * * @since 4.0 */ public class Sorter implements Comparator { /** * NULL is a Sorter that leaves elements in an undefined order */ public static Sorter NULL = new Sorter(new Comparator() { public int compare(Description o1, Description o2) { return 0; } }); private final Comparator fComparator; /** * Creates a Sorter that uses comparator * to sort tests * * @param comparator the {@link Comparator} to use when sorting tests */ public Sorter(Comparator comparator) { fComparator = comparator; } /** * Sorts the test in runner using comparator */ public void apply(Object object) { if (object instanceof Sortable) { Sortable sortable = (Sortable) object; sortable.sort(this); } } public int compare(Description o1, Description o2) { return fComparator.compare(o1, o2); } } junit4-4.11/src/main/java/org/junit/runner/manipulation/Sortable.java0000644000175000017500000000121512050524441025203 0ustar ebourgebourgpackage org.junit.runner.manipulation; /** * Interface for runners that allow sorting of tests. By sorting tests based on when they last failed, most recently * failed first, you can reduce the average time to the first test failing. Test sorting should not be used to * cope with order dependencies between tests. Tests that are isolated from each other are less * expensive to maintain and can be run individually. * * @since 4.0 */ public interface Sortable { /** * Sorts the tests using sorter * * @param sorter the {@link Sorter} to use for sorting the tests */ public void sort(Sorter sorter); } junit4-4.11/src/main/java/org/junit/runner/notification/0000755000175000017500000000000012050524441022554 5ustar ebourgebourgjunit4-4.11/src/main/java/org/junit/runner/notification/package-info.java0000644000175000017500000000015112050524441025740 0ustar ebourgebourg/** * Provides information about a test run. * * @since 4.0 */ package org.junit.runner.notification;junit4-4.11/src/main/java/org/junit/runner/notification/Failure.java0000644000175000017500000000463412050524441025015 0ustar ebourgebourgpackage org.junit.runner.notification; import java.io.PrintWriter; import java.io.Serializable; import java.io.StringWriter; import org.junit.runner.Description; /** * A Failure holds a description of the failed test and the * exception that was thrown while running it. In most cases the {@link org.junit.runner.Description} * will be of a single test. However, if problems are encountered while constructing the * test (for example, if a {@link org.junit.BeforeClass} method is not static), it may describe * something other than a single test. * * @since 4.0 */ public class Failure implements Serializable { private static final long serialVersionUID = 1L; private final Description fDescription; private final Throwable fThrownException; /** * Constructs a Failure with the given description and exception. * * @param description a {@link org.junit.runner.Description} of the test that failed * @param thrownException the exception that was thrown while running the test */ public Failure(Description description, Throwable thrownException) { fThrownException = thrownException; fDescription = description; } /** * @return a user-understandable label for the test */ public String getTestHeader() { return fDescription.getDisplayName(); } /** * @return the raw description of the context of the failure. */ public Description getDescription() { return fDescription; } /** * @return the exception thrown */ public Throwable getException() { return fThrownException; } @Override public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(getTestHeader() + ": " + fThrownException.getMessage()); return buffer.toString(); } /** * Convenience method * * @return the printed form of the exception */ public String getTrace() { StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); getException().printStackTrace(writer); StringBuffer buffer = stringWriter.getBuffer(); return buffer.toString(); } /** * Convenience method * * @return the message of the thrown exception */ public String getMessage() { return getException().getMessage(); } } junit4-4.11/src/main/java/org/junit/runner/notification/RunListener.java0000644000175000017500000000551212050524441025674 0ustar ebourgebourgpackage org.junit.runner.notification; import org.junit.internal.AssumptionViolatedException; import org.junit.runner.Description; import org.junit.runner.Result; /** *

    If you need to respond to the events during a test run, extend RunListener * and override the appropriate methods. If a listener throws an exception while processing a * test event, it will be removed for the remainder of the test run.

    * *

    For example, suppose you have a Cowbell * class that you want to make a noise whenever a test fails. You could write: *

     * public class RingingListener extends RunListener {
     *    public void testFailure(Failure failure) {
     *       Cowbell.ring();
     *    }
     * }
     * 
    *

    * *

    To invoke your listener, you need to run your tests through JUnitCore. *

     * public void main(String... args) {
     *    JUnitCore core= new JUnitCore();
     *    core.addListener(new RingingListener());
     *    core.run(MyTestClass.class);
     * }
     * 
    *

    * * @see org.junit.runner.JUnitCore * @since 4.0 */ public class RunListener { /** * Called before any tests have been run. * * @param description describes the tests to be run */ public void testRunStarted(Description description) throws Exception { } /** * Called when all tests have finished * * @param result the summary of the test run, including all the tests that failed */ public void testRunFinished(Result result) throws Exception { } /** * Called when an atomic test is about to be started. * * @param description the description of the test that is about to be run * (generally a class and method name) */ public void testStarted(Description description) throws Exception { } /** * Called when an atomic test has finished, whether the test succeeds or fails. * * @param description the description of the test that just ran */ public void testFinished(Description description) throws Exception { } /** * Called when an atomic test fails. * * @param failure describes the test that failed and the exception that was thrown */ public void testFailure(Failure failure) throws Exception { } /** * Called when an atomic test flags that it assumes a condition that is * false * * @param failure describes the test that failed and the * {@link AssumptionViolatedException} that was thrown */ public void testAssumptionFailure(Failure failure) { } /** * Called when a test will not be run, generally because a test method is annotated * with {@link org.junit.Ignore}. * * @param description describes the test that will not be run */ public void testIgnored(Description description) throws Exception { } } junit4-4.11/src/main/java/org/junit/runner/notification/RunNotifier.java0000644000175000017500000001513512050524441025670 0ustar ebourgebourgpackage org.junit.runner.notification; import static java.util.Arrays.asList; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.junit.internal.AssumptionViolatedException; import org.junit.runner.Description; import org.junit.runner.Result; /** * If you write custom runners, you may need to notify JUnit of your progress running tests. * Do this by invoking the RunNotifier passed to your implementation of * {@link org.junit.runner.Runner#run(RunNotifier)}. Future evolution of this class is likely to * move {@link #fireTestRunStarted(Description)} and {@link #fireTestRunFinished(Result)} * to a separate class since they should only be called once per run. * * @since 4.0 */ public class RunNotifier { private final List fListeners = Collections.synchronizedList(new ArrayList()); private volatile boolean fPleaseStop = false; /** * Internal use only */ public void addListener(RunListener listener) { fListeners.add(listener); } /** * Internal use only */ public void removeListener(RunListener listener) { fListeners.remove(listener); } private abstract class SafeNotifier { private final List fCurrentListeners; SafeNotifier() { this(fListeners); } SafeNotifier(List currentListeners) { fCurrentListeners = currentListeners; } void run() { synchronized (fListeners) { List safeListeners = new ArrayList(); List failures = new ArrayList(); for (Iterator all = fCurrentListeners.iterator(); all .hasNext(); ) { try { RunListener listener = all.next(); notifyListener(listener); safeListeners.add(listener); } catch (Exception e) { failures.add(new Failure(Description.TEST_MECHANISM, e)); } } fireTestFailures(safeListeners, failures); } } abstract protected void notifyListener(RunListener each) throws Exception; } /** * Do not invoke. */ public void fireTestRunStarted(final Description description) { new SafeNotifier() { @Override protected void notifyListener(RunListener each) throws Exception { each.testRunStarted(description); } ; }.run(); } /** * Do not invoke. */ public void fireTestRunFinished(final Result result) { new SafeNotifier() { @Override protected void notifyListener(RunListener each) throws Exception { each.testRunFinished(result); } ; }.run(); } /** * Invoke to tell listeners that an atomic test is about to start. * * @param description the description of the atomic test (generally a class and method name) * @throws StoppedByUserException thrown if a user has requested that the test run stop */ public void fireTestStarted(final Description description) throws StoppedByUserException { if (fPleaseStop) { throw new StoppedByUserException(); } new SafeNotifier() { @Override protected void notifyListener(RunListener each) throws Exception { each.testStarted(description); } ; }.run(); } /** * Invoke to tell listeners that an atomic test failed. * * @param failure the description of the test that failed and the exception thrown */ public void fireTestFailure(Failure failure) { fireTestFailures(fListeners, asList(failure)); } private void fireTestFailures(List listeners, final List failures) { if (!failures.isEmpty()) { new SafeNotifier(listeners) { @Override protected void notifyListener(RunListener listener) throws Exception { for (Failure each : failures) { listener.testFailure(each); } } ; }.run(); } } /** * Invoke to tell listeners that an atomic test flagged that it assumed * something false. * * @param failure the description of the test that failed and the * {@link AssumptionViolatedException} thrown */ public void fireTestAssumptionFailed(final Failure failure) { new SafeNotifier() { @Override protected void notifyListener(RunListener each) throws Exception { each.testAssumptionFailure(failure); } ; }.run(); } /** * Invoke to tell listeners that an atomic test was ignored. * * @param description the description of the ignored test */ public void fireTestIgnored(final Description description) { new SafeNotifier() { @Override protected void notifyListener(RunListener each) throws Exception { each.testIgnored(description); } }.run(); } /** * Invoke to tell listeners that an atomic test finished. Always invoke * {@link #fireTestFinished(Description)} if you invoke {@link #fireTestStarted(Description)} * as listeners are likely to expect them to come in pairs. * * @param description the description of the test that finished */ public void fireTestFinished(final Description description) { new SafeNotifier() { @Override protected void notifyListener(RunListener each) throws Exception { each.testFinished(description); } ; }.run(); } /** * Ask that the tests run stop before starting the next test. Phrased politely because * the test currently running will not be interrupted. It seems a little odd to put this * functionality here, but the RunNotifier is the only object guaranteed * to be shared amongst the many runners involved. */ public void pleaseStop() { fPleaseStop = true; } /** * Internal use only. The Result's listener must be first. */ public void addFirstListener(RunListener listener) { fListeners.add(0, listener); } }junit4-4.11/src/main/java/org/junit/runner/notification/StoppedByUserException.java0000644000175000017500000000061012050524441030043 0ustar ebourgebourgpackage org.junit.runner.notification; /** * Thrown when a user has requested that the test run stop. Writers of * test running GUIs should be prepared to catch a StoppedByUserException. * * @see org.junit.runner.notification.RunNotifier * @since 4.0 */ public class StoppedByUserException extends RuntimeException { private static final long serialVersionUID = 1L; } junit4-4.11/src/main/java/org/junit/runner/RunWith.java0000644000175000017500000000230512050524441022331 0ustar ebourgebourgpackage org.junit.runner; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * When a class is annotated with @RunWith or extends a class annotated * with @RunWith, JUnit will invoke the class it references to run the * tests in that class instead of the runner built into JUnit. We added this feature late * in development. While it seems powerful we expect the runner API to change as we learn * how people really use it. Some of the classes that are currently internal will likely * be refined and become public. * * For example, suites in JUnit 4 are built using RunWith, and a custom runner named Suite: * *
     * @RunWith(Suite.class)
     * @SuiteClasses({ATest.class, BTest.class, CTest.class})
     * public class ABCSuite {
     * }
     * 
    * * @since 4.0 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Inherited public @interface RunWith { /** * @return a Runner class (must have a constructor that takes a single Class to run) */ Class value(); } junit4-4.11/src/main/java/org/junit/runner/Computer.java0000644000175000017500000000242312050524441022530 0ustar ebourgebourgpackage org.junit.runner; import org.junit.runners.Suite; import org.junit.runners.model.InitializationError; import org.junit.runners.model.RunnerBuilder; /** * Represents a strategy for computing runners and suites. * WARNING: this class is very likely to undergo serious changes in version 4.8 and * beyond. * * @since 4.6 */ public class Computer { /** * Returns a new default computer, which runs tests in serial order */ public static Computer serial() { return new Computer(); } /** * Create a suite for {@code classes}, building Runners with {@code builder}. * Throws an InitializationError if Runner construction fails */ public Runner getSuite(final RunnerBuilder builder, Class[] classes) throws InitializationError { return new Suite(new RunnerBuilder() { @Override public Runner runnerForClass(Class testClass) throws Throwable { return getRunner(builder, testClass); } }, classes); } /** * Create a single-class runner for {@code testClass}, using {@code builder} */ protected Runner getRunner(RunnerBuilder builder, Class testClass) throws Throwable { return builder.runnerForClass(testClass); } } junit4-4.11/src/main/java/org/junit/runner/Request.java0000644000175000017500000001446412050524441022372 0ustar ebourgebourgpackage org.junit.runner; import java.util.Comparator; import org.junit.internal.builders.AllDefaultPossibilitiesBuilder; import org.junit.internal.requests.ClassRequest; import org.junit.internal.requests.FilterRequest; import org.junit.internal.requests.SortingRequest; import org.junit.internal.runners.ErrorReportingRunner; import org.junit.runner.manipulation.Filter; import org.junit.runners.model.InitializationError; /** *

    A Request is an abstract description of tests to be run. Older versions of * JUnit did not need such a concept--tests to be run were described either by classes containing * tests or a tree of {@link org.junit.Test}s. However, we want to support filtering and sorting, * so we need a more abstract specification than the tests themselves and a richer * specification than just the classes.

    * *

    The flow when JUnit runs tests is that a Request specifies some tests to be run -> * a {@link org.junit.runner.Runner} is created for each class implied by the Request -> * the {@link org.junit.runner.Runner} returns a detailed {@link org.junit.runner.Description} * which is a tree structure of the tests to be run.

    * * @since 4.0 */ public abstract class Request { /** * Create a Request that, when processed, will run a single test. * This is done by filtering out all other tests. This method is used to support rerunning * single tests. * * @param clazz the class of the test * @param methodName the name of the test * @return a Request that will cause a single test be run */ public static Request method(Class clazz, String methodName) { Description method = Description.createTestDescription(clazz, methodName); return Request.aClass(clazz).filterWith(method); } /** * Create a Request that, when processed, will run all the tests * in a class. The odd name is necessary because class is a reserved word. * * @param clazz the class containing the tests * @return a Request that will cause all tests in the class to be run */ public static Request aClass(Class clazz) { return new ClassRequest(clazz); } /** * Create a Request that, when processed, will run all the tests * in a class. If the class has a suite() method, it will be ignored. * * @param clazz the class containing the tests * @return a Request that will cause all tests in the class to be run */ public static Request classWithoutSuiteMethod(Class clazz) { return new ClassRequest(clazz, false); } /** * Create a Request that, when processed, will run all the tests * in a set of classes. * * @param computer Helps construct Runners from classes * @param classes the classes containing the tests * @return a Request that will cause all tests in the classes to be run */ public static Request classes(Computer computer, Class... classes) { try { AllDefaultPossibilitiesBuilder builder = new AllDefaultPossibilitiesBuilder(true); Runner suite = computer.getSuite(builder, classes); return runner(suite); } catch (InitializationError e) { throw new RuntimeException( "Bug in saff's brain: Suite constructor, called as above, should always complete"); } } /** * Create a Request that, when processed, will run all the tests * in a set of classes with the default Computer. * * @param classes the classes containing the tests * @return a Request that will cause all tests in the classes to be run */ public static Request classes(Class... classes) { return classes(JUnitCore.defaultComputer(), classes); } /** * Not used within JUnit. Clients should simply instantiate ErrorReportingRunner themselves */ @Deprecated public static Request errorReport(Class klass, Throwable cause) { return runner(new ErrorReportingRunner(klass, cause)); } /** * @param runner the runner to return * @return a Request that will run the given runner when invoked */ public static Request runner(final Runner runner) { return new Request() { @Override public Runner getRunner() { return runner; } }; } /** * Returns a {@link Runner} for this Request * * @return corresponding {@link Runner} for this Request */ public abstract Runner getRunner(); /** * Returns a Request that only contains those tests that should run when * filter is applied * * @param filter The {@link Filter} to apply to this Request * @return the filtered Request */ public Request filterWith(Filter filter) { return new FilterRequest(this, filter); } /** * Returns a Request that only runs contains tests whose {@link Description} * equals desiredDescription * * @param desiredDescription {@link Description} of those tests that should be run * @return the filtered Request */ public Request filterWith(final Description desiredDescription) { return filterWith(Filter.matchMethodDescription(desiredDescription)); } /** * Returns a Request whose Tests can be run in a certain order, defined by * comparator * * For example, here is code to run a test suite in alphabetical order: * *
         * private static Comparator forward() {
         * return new Comparator() {
         * public int compare(Description o1, Description o2) {
         * return o1.getDisplayName().compareTo(o2.getDisplayName());
         * }
         * };
         * }
         *
         * public static main() {
         * new JUnitCore().run(Request.aClass(AllTests.class).sortWith(forward()));
         * }
         * 
    * * @param comparator definition of the order of the tests in this Request * @return a Request with ordered Tests */ public Request sortWith(Comparator comparator) { return new SortingRequest(this, comparator); } } junit4-4.11/src/main/java/org/junit/runner/Describable.java0000644000175000017500000000043112050524441023126 0ustar ebourgebourgpackage org.junit.runner; /** * Represents an object that can describe itself * * @since 4.5 */ public interface Describable { /** * @return a {@link Description} showing the tests to be run by the receiver */ public abstract Description getDescription(); }junit4-4.11/src/main/java/org/junit/runner/Runner.java0000644000175000017500000000276112050524441022210 0ustar ebourgebourgpackage org.junit.runner; import org.junit.runner.notification.RunNotifier; /** * A Runner runs tests and notifies a {@link org.junit.runner.notification.RunNotifier} * of significant events as it does so. You will need to subclass Runner * when using {@link org.junit.runner.RunWith} to invoke a custom runner. When creating * a custom runner, in addition to implementing the abstract methods here you must * also provide a constructor that takes as an argument the {@link Class} containing * the tests. *

    * The default runner implementation guarantees that the instances of the test case * class will be constructed immediately before running the test and that the runner * will retain no reference to the test case instances, generally making them * available for garbage collection. * * @see org.junit.runner.Description * @see org.junit.runner.RunWith * @since 4.0 */ public abstract class Runner implements Describable { /* * (non-Javadoc) * @see org.junit.runner.Describable#getDescription() */ public abstract Description getDescription(); /** * Run the tests for this runner. * * @param notifier will be notified of events while tests are being run--tests being * started, finishing, and failing */ public abstract void run(RunNotifier notifier); /** * @return the number of tests to be run by the receiver */ public int testCount() { return getDescription().testCount(); } }junit4-4.11/src/main/java/org/junit/Before.java0000644000175000017500000000214512050524441020624 0ustar ebourgebourgpackage org.junit; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** *

    When writing tests, it is common to find that several tests need similar * objects created before they can run. Annotating a public void method * with @Before causes that method to be run before the {@link org.junit.Test} method. * The @Before methods of superclasses will be run before those of the current class, * unless they are overridden in the current class. No other ordering is defined. *

    * * Here is a simple example: *
     * public class Example {
     *    List empty;
     *    @Before public void initialize() {
     *       empty= new ArrayList();
     *    }
     *    @Test public void size() {
     *       ...
     *    }
     *    @Test public void remove() {
     *       ...
     *    }
     * }
     * 
    * * @see org.junit.BeforeClass * @see org.junit.After * @since 4.0 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Before { } junit4-4.11/src/main/java/org/junit/matchers/0000755000175000017500000000000012050524441020363 5ustar ebourgebourgjunit4-4.11/src/main/java/org/junit/matchers/JUnitMatchers.java0000644000175000017500000001032412050524441023746 0ustar ebourgebourgpackage org.junit.matchers; import org.hamcrest.CoreMatchers; import org.hamcrest.Matcher; import org.hamcrest.core.CombinableMatcher.CombinableBothMatcher; import org.hamcrest.core.CombinableMatcher.CombinableEitherMatcher; import org.junit.internal.matchers.StacktracePrintingMatcher; /** * Convenience import class: these are useful matchers for use with the assertThat method, but they are * not currently included in the basic CoreMatchers class from hamcrest. * * @since 4.4 */ public class JUnitMatchers { /** * @return A matcher matching any collection containing element * @deprecated Please use {@link CoreMatchers#hasItem(Object)} instead. */ @Deprecated public static Matcher> hasItem(T element) { return CoreMatchers.hasItem(element); } /** * @return A matcher matching any collection containing an element matching elementMatcher * @deprecated Please use {@link CoreMatchers#hasItem(Matcher)} instead. */ @Deprecated public static Matcher> hasItem(Matcher elementMatcher) { return CoreMatchers.hasItem(elementMatcher); } /** * @return A matcher matching any collection containing every element in elements * @deprecated Please use {@link CoreMatchers#hasItems(Object...)} instead. */ @Deprecated public static Matcher> hasItems(T... elements) { return CoreMatchers.hasItems(elements); } /** * @return A matcher matching any collection containing at least one element that matches * each matcher in elementMatcher (this may be one element matching all matchers, * or different elements matching each matcher) * @deprecated Please use {@link CoreMatchers#hasItems(Matcher...)} instead. */ @Deprecated public static Matcher> hasItems(Matcher... elementMatchers) { return CoreMatchers.hasItems(elementMatchers); } /** * @return A matcher matching any collection in which every element matches elementMatcher * @deprecated Please use {@link CoreMatchers#everyItem(Matcher)} instead. */ @Deprecated public static Matcher> everyItem(final Matcher elementMatcher) { return CoreMatchers.everyItem(elementMatcher); } /** * @return a matcher matching any string that contains substring * @deprecated Please use {@link CoreMatchers#containsString(String)} instead. */ @Deprecated public static Matcher containsString(java.lang.String substring) { return CoreMatchers.containsString(substring); } /** * This is useful for fluently combining matchers that must both pass. For example: *
         *   assertThat(string, both(containsString("a")).and(containsString("b")));
         * 
    * * @deprecated Please use {@link CoreMatchers#both(Matcher)} instead. */ @Deprecated public static CombinableBothMatcher both(Matcher matcher) { return CoreMatchers.both(matcher); } /** * This is useful for fluently combining matchers where either may pass, for example: *
         *   assertThat(string, either(containsString("a")).or(containsString("b")));
         * 
    * * @deprecated Please use {@link CoreMatchers#either(Matcher)} instead. */ @Deprecated public static CombinableEitherMatcher either(Matcher matcher) { return CoreMatchers.either(matcher); } /** * @return A matcher that delegates to throwableMatcher and in addition * appends the stacktrace of the actual Throwable in case of a mismatch. */ public static Matcher isThrowable(Matcher throwableMatcher) { return StacktracePrintingMatcher.isThrowable(throwableMatcher); } /** * @return A matcher that delegates to exceptionMatcher and in addition * appends the stacktrace of the actual Exception in case of a mismatch. */ public static Matcher isException(Matcher exceptionMatcher) { return StacktracePrintingMatcher.isException(exceptionMatcher); } } junit4-4.11/src/main/java/org/junit/matchers/package-info.java0000644000175000017500000000037412050524441023556 0ustar ebourgebourg/** * Provides useful additional {@link org.hamcrest.Matcher}s for use with * the {@link org.junit.Assert#assertThat(Object, org.hamcrest.Matcher)} * statement * * @since 4.0 * @see org.junit.matchers.JUnitMatchers */ package org.junit.matchers;junit4-4.11/src/main/java/org/junit/runners/0000755000175000017500000000000012050524441020251 5ustar ebourgebourgjunit4-4.11/src/main/java/org/junit/runners/ParentRunner.java0000644000175000017500000003255512050524441023551 0ustar ebourgebourgpackage org.junit.runners; import static org.junit.internal.runners.rules.RuleFieldValidator.CLASS_RULE_METHOD_VALIDATOR; import static org.junit.internal.runners.rules.RuleFieldValidator.CLASS_RULE_VALIDATOR; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Rule; import org.junit.internal.AssumptionViolatedException; import org.junit.internal.runners.model.EachTestNotifier; import org.junit.internal.runners.statements.RunAfters; import org.junit.internal.runners.statements.RunBefores; import org.junit.rules.RunRules; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runner.Runner; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.Filterable; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runner.manipulation.Sortable; import org.junit.runner.manipulation.Sorter; import org.junit.runner.notification.RunNotifier; import org.junit.runner.notification.StoppedByUserException; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.MultipleFailureException; import org.junit.runners.model.RunnerScheduler; import org.junit.runners.model.Statement; import org.junit.runners.model.TestClass; /** * Provides most of the functionality specific to a Runner that implements a * "parent node" in the test tree, with children defined by objects of some data * type {@code T}. (For {@link BlockJUnit4ClassRunner}, {@code T} is * {@link Method} . For {@link Suite}, {@code T} is {@link Class}.) Subclasses * must implement finding the children of the node, describing each child, and * running each child. ParentRunner will filter and sort children, handle * {@code @BeforeClass} and {@code @AfterClass} methods, * handle annotated {@link ClassRule}s, create a composite * {@link Description}, and run children sequentially. * * @since 4.5 */ public abstract class ParentRunner extends Runner implements Filterable, Sortable { private final TestClass fTestClass; private Sorter fSorter = Sorter.NULL; private List fFilteredChildren = null; private RunnerScheduler fScheduler = new RunnerScheduler() { public void schedule(Runnable childStatement) { childStatement.run(); } public void finished() { // do nothing } }; /** * Constructs a new {@code ParentRunner} that will run {@code @TestClass} */ protected ParentRunner(Class testClass) throws InitializationError { fTestClass = new TestClass(testClass); validate(); } // // Must be overridden // /** * Returns a list of objects that define the children of this Runner. */ protected abstract List getChildren(); /** * Returns a {@link Description} for {@code child}, which can be assumed to * be an element of the list returned by {@link ParentRunner#getChildren()} */ protected abstract Description describeChild(T child); /** * Runs the test corresponding to {@code child}, which can be assumed to be * an element of the list returned by {@link ParentRunner#getChildren()}. * Subclasses are responsible for making sure that relevant test events are * reported through {@code notifier} */ protected abstract void runChild(T child, RunNotifier notifier); // // May be overridden // /** * Adds to {@code errors} a throwable for each problem noted with the test class (available from {@link #getTestClass()}). * Default implementation adds an error for each method annotated with * {@code @BeforeClass} or {@code @AfterClass} that is not * {@code public static void} with no arguments. */ protected void collectInitializationErrors(List errors) { validatePublicVoidNoArgMethods(BeforeClass.class, true, errors); validatePublicVoidNoArgMethods(AfterClass.class, true, errors); validateClassRules(errors); } /** * Adds to {@code errors} if any method in this class is annotated with * {@code annotation}, but: *