### Test JUnit Installation Source: https://github.com/junit-team/junit4/wiki/FAQ Run this command to execute the sample tests included with JUnit. This verifies that JUnit is correctly installed and accessible via the CLASSPATH. The JUnit installation directory must be on the CLASSPATH. ```java java org.junit.runner.JUnitCore org.junit.tests.AllTests ``` -------------------------------- ### Test Fixture Setup Source: https://github.com/junit-team/junit4/blob/main/doc/testinfected/testing.htm Set up the test fixture by initializing Money and MoneyBag objects. This is typically done in a setUp method before each test case runs. ```java 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); } ``` -------------------------------- ### Set Up Test Fixture with setUp Method in JUnit 4 Source: https://github.com/junit-team/junit4/blob/main/doc/testinfected/testing.htm This snippet demonstrates how to use the setUp method in JUnit 4 to initialize instance variables, creating a common test fixture for multiple test cases. This promotes code reuse and avoids setup duplication. ```java public class MoneyTest extends TestCase { private Money f12CHF; private Money f14CHF; protected void setUp() { f12CHF= new Money(12, "CHF"); f14CHF= new Money(14, "CHF"); } } ``` -------------------------------- ### Default Implementations for Test Setup and Teardown Source: https://github.com/junit-team/junit4/blob/main/doc/cookstour/cookstour.htm Provides default, no-operation implementations for setUp(), runTest(), and tearDown() methods in TestCase. These are intended to be overridden by subclasses. ```java protected void runTest() { } protected void setUp() { } protected void tearDown() { } ``` -------------------------------- ### Create TestSuite Manually Source: https://github.com/junit-team/junit4/blob/main/doc/cookstour/cookstour.htm Example of manually creating a TestSuite and adding specific test cases to it. ```java public static Test suite() { TestSuite suite= new TestSuite(); suite.addTest(new MoneyTest("testMoneyEquals")); suite.addTest(new MoneyTest("testSimpleAdd")); } ``` -------------------------------- ### Basic assertThat Examples Source: https://github.com/junit-team/junit4/wiki/Matchers-and-assertThat Demonstrates the basic syntax of assertThat with common matchers like is, not, either, and hasItem. ```java assertThat(x, is(3)); ``` ```java assertThat(x, is(not(4))); ``` ```java assertThat(responseString, either(containsString("color")).or(containsString("colour"))); ``` ```java assertThat(myList, hasItem("3")); ``` -------------------------------- ### Test Suite Setup Source: https://github.com/junit-team/junit4/blob/main/doc/testinfected/testing.htm Configures a TestSuite to include various Money and MoneyBag related test cases. ```java 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; } ``` -------------------------------- ### Expected Output of Fixture Example Source: https://github.com/junit-team/junit4/wiki/Test-fixtures The expected console output when running the TestFixturesExample class, illustrating the order of execution for class and method-level fixture annotations. ```text @BeforeClass setUpClass @Before setUp @Test test2() @After tearDown @Before setUp @Test test1() @After tearDown @AfterClass tearDownClass ``` -------------------------------- ### Example of code that should throw an exception Source: https://github.com/junit-team/junit4/wiki/Exception-testing This code snippet demonstrates an operation that is expected to throw an IndexOutOfBoundsException. ```java new ArrayList().get(0); ``` -------------------------------- ### Forwarding Parameters Example Source: https://github.com/junit-team/junit4/wiki/FAQ This method is too simple to break as it only forwards parameters to another object. Testing should focus on the collaborator object if its behavior is in question. ```java public void myMethod(final int a, final String b) { myCollaborator.anotherMethod(a, b); } ``` -------------------------------- ### JUnit 4 Fixture Example Source: https://github.com/junit-team/junit4/wiki/Test-fixtures Demonstrates the usage of @BeforeClass, @AfterClass, @Before, and @After annotations for managing test fixtures. These annotations help in setting up and cleaning up resources before and after tests run. ```java package test; import java.io.Closeable; import java.io.IOException; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class TestFixturesExample { static class ExpensiveManagedResource implements Closeable { @Override public void close() throws IOException {} } static class ManagedResource implements Closeable { @Override public void close() throws IOException {} } @BeforeClass public static void setUpClass() { System.out.println("@BeforeClass setUpClass"); myExpensiveManagedResource = new ExpensiveManagedResource(); } @AfterClass public static void tearDownClass() throws IOException { System.out.println("@AfterClass tearDownClass"); myExpensiveManagedResource.close(); myExpensiveManagedResource = null; } private ManagedResource myManagedResource; private static ExpensiveManagedResource myExpensiveManagedResource; private void println(String string) { System.out.println(string); } @Before public void setUp() { this.println("@Before setUp"); this.myManagedResource = new ManagedResource(); } @After public void tearDown() throws IOException { this.println("@After tearDown"); this.myManagedResource.close(); this.myManagedResource = null; } @Test public void test1() { this.println("@Test test1()"); } @Test public void test2() { this.println("@Test test2()"); } } ``` -------------------------------- ### Sample test method Source: https://github.com/junit-team/junit4/blob/main/doc/cookstour/cookstour.htm An example test method demonstrating the use of assertion methods like assertTrue and assertEquals. It does not require direct knowledge of TestResult. ```java public void testMoneyEquals() { assertTrue(!f12CHF.equals(null)); assertEquals(f12CHF, f12CHF); assertEquals(f12CHF, new Money(12, "CHF")); assertTrue(!f12CHF.equals(f14CHF)); } ``` -------------------------------- ### Basic JUnit Test Template with Setup and Teardown Source: https://github.com/junit-team/junit4/wiki/FAQ A fundamental template for creating JUnit tests. It includes necessary imports and demonstrates the use of @Before and @After annotations for setting up and tearing down test fixtures before and after each test method. ```java 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 ``` -------------------------------- ### JUnit Test Fixture Setup Source: https://github.com/junit-team/junit4/blob/main/src/site/markdown/cookbook.md Use @Before to initialize test fixture fields before each test and @After to release resources. Fields are declared at the class level. ```java 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"); } } ``` -------------------------------- ### Set CLASSPATH for JUnit (Windows) Source: https://github.com/junit-team/junit4/wiki/FAQ Example of setting the CLASSPATH environment variable on Windows to include JUnit JARs, project classes, and dependent libraries. ```batch set CLASSPATH=%JUNIT_HOME%\junit.jar;c:\myproject\classes;c:\myproject\lib\something.jar ``` -------------------------------- ### JUnit 4 test class structure with setup and teardown Source: https://github.com/junit-team/junit4/wiki/FAQ Demonstrates the use of @BeforeClass, @AfterClass, @Before, and @After annotations for managing test fixtures. @BeforeClass and @AfterClass run once per class, while @Before and @After run before and after each test method, respectively. ```java 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()); } } ``` -------------------------------- ### Rewrite TestEquals Using Test Fixture Source: https://github.com/junit-team/junit4/blob/main/doc/testinfected/testing.htm This test case, rewritten to use the setUp method for fixture initialization, verifies the equality of Money objects. It leverages the pre-initialized f12CHF and f14CHF instance variables. ```java public void testEquals() { Assert.assertTrue(!f12CHF.equals(null)); Assert.assertEquals(f12CHF, f12CHF); Assert.assertEquals(f12CHF, new Money(12, "CHF")); Assert.assertTrue(!f12CHF.equals(f14CHF)); } ``` -------------------------------- ### Set CLASSPATH for JUnit (Unix/Bash) Source: https://github.com/junit-team/junit4/wiki/FAQ Example of setting the CLASSPATH environment variable on Unix-like systems (bash) to include JUnit JARs, project classes, and dependent libraries. ```bash export CLASSPATH=$JUNIT_HOME/junit.jar:/myproject/classes:/myproject/lib/something.jar ``` -------------------------------- ### Test Exception Message with Matchers Source: https://github.com/junit-team/junit4/wiki/Exception-testing This example demonstrates using Hamcrest Matchers with `expectMessage` for more flexible exception message validation. It requires importing `CoreMatchers`. ```java thrown.expectMessage(CoreMatchers.containsString("Size: 0")); ``` -------------------------------- ### TestResult.startTest() Method Source: https://github.com/junit-team/junit4/blob/main/doc/cookstour/cookstour.htm Synchronized method in TestResult to record the start of a test. It increments the count of run tests. ```java public synchronized void startTest(Test test) { fRunTests++; } ``` -------------------------------- ### Template Method for TestCase.run() Source: https://github.com/junit-team/junit4/blob/main/doc/cookstour/cookstour.htm Implements the Template Method pattern to define the skeleton of a test execution algorithm. Subclasses can override setUp(), runTest(), and tearDown() without altering the algorithm's structure. ```java public void run() { setUp(); runTest(); tearDown(); } ``` -------------------------------- ### Rewrite TestSimpleAdd Using Test Fixture Source: https://github.com/junit-team/junit4/blob/main/doc/testinfected/testing.htm This test case, refactored to use the setUp method for fixture initialization, tests the addition of two Money objects. It uses the f12CHF and f14CHF instance variables for the operation. ```java public void testSimpleAdd() { Money expected= new Money(26, "CHF"); Money result= f12CHF.add(f14CHF); Assert.assertTrue(expected.equals(result)); } ``` -------------------------------- ### Execute a single test case Source: https://github.com/junit-team/junit4/blob/main/doc/cookstour/cookstour.htm Runs a single test case, handling assertions failures and other errors. It ensures setup and tearDown are always called. ```java 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(); } } ``` -------------------------------- ### Example Test with Talkative JUnit Source: https://github.com/junit-team/junit4/wiki/Quo-Vadis-JUnit A sample test case demonstrating the use of Talkative JUnit, which allows for more descriptive test names and potentially richer reporting. ```java package com.github.stefanbirkner.junit.talkative; import static org.junit.Assert.assertEquals; import org.junit.Test; public class ExampleTest { @Test public void should_return_true_when_given_true() throws Exception { assertEquals(true, true); } } ``` -------------------------------- ### Test Exception with Properties using Matchers Source: https://github.com/junit-team/junit4/wiki/Exception-testing This comprehensive example shows how to test for a specific exception type, message content, and nested properties of the exception using Hamcrest Matchers. It includes necessary imports and a helper class. ```java import static org.hamcrest.Matchers.hasProperty; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.startsWith; import javax.ws.rs.NotFoundException; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class TestExy { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void shouldThrow() { TestThing testThing = new TestThing(); thrown.expect(NotFoundException.class); thrown.expectMessage(startsWith("some Message")); thrown.expect(hasProperty("response", hasProperty("status", is(404)))); testThing.chuck(); } private class TestThing { public void chuck() { Response response = Response.status(Status.NOT_FOUND).entity("Resource not found").build(); throw new NotFoundException("some Message", response); } } } ``` -------------------------------- ### Closure-based Test Example in Java Source: https://github.com/junit-team/junit4/wiki/Quo-Vadis-JUnit Illustrates a potential future syntax for JUnit tests using closures (lambda expressions) for defining test logic. Requires a custom test class extending JUnitTest. ```java public class SomeTest extends JUnitTest {{ test ("Test something", () -> { assertEquals(1, 1); }); test ("Test something else", () -> { assertEquals(2, 2); }); }} ``` -------------------------------- ### Test Constructor with Get Method in JUnit 4 Source: https://github.com/junit-team/junit4/wiki/FAQ This snippet demonstrates testing a constructor by verifying the state of an object immediately after creation using its getter method. This is useful when concerned about initial property values. ```java @Test public void testCreate() { assertEquals(23, new MyClass(23).getX()); } ``` -------------------------------- ### Add JUnit to Classpath on Windows Source: https://github.com/junit-team/junit4/wiki/FAQ This command adds the JUnit JAR file to the system's CLASSPATH environment variable on Windows. Ensure %JUNIT_HOME% is set to your JUnit installation directory. ```batch set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%\junit.jar ``` -------------------------------- ### Add JUnit to Classpath on Unix Source: https://github.com/junit-team/junit4/wiki/FAQ This command adds the JUnit JAR file to the CLASSPATH environment variable on Unix-like systems using bash. Ensure $JUNIT_HOME is set to your JUnit installation directory. ```bash export CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit.jar ``` -------------------------------- ### Popper Theory Using Custom Range Supplier Source: https://github.com/junit-team/junit4/wiki/Theories Example of a Popper theory that utilizes the custom @Between annotation to supply data points as a range of integers. This demonstrates how to use custom parameter suppliers for theories. ```java @Theory public void multiplyIsInverseOfDivideWithInlineDataPoints( ``` -------------------------------- ### Test Simple Add Operation in JUnit 4 Source: https://github.com/junit-team/junit4/blob/main/doc/testinfected/testing.htm This snippet demonstrates a simple test case for adding two Money objects and verifying the result using JUnit assertions. It includes fixture setup, operation execution, and result verification. ```java Money m12CHF= new Money(12, "CHF"); Money m14CHF= new Money(14, "CHF"); Money expected= new Money(26, "CHF"); Money result= m12CHF.add(m14CHF); Assert.assertTrue(expected.equals(result)); ``` -------------------------------- ### JUnit 4 Theory Test Example Source: https://github.com/junit-team/junit4/wiki/Theories This example demonstrates a JUnit 4 theory test using `@RunWith(Theories.class)`. It defines data points and a theory that asserts a condition based on these data points, with an assumption to filter out specific cases. Use this for testing general behavior across various inputs. ```java @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)); } } ``` -------------------------------- ### Importing Hamcrest Matchers Source: https://github.com/junit-team/junit4/wiki/Matchers-and-assertThat Shows how to import Hamcrest matchers using static imports for use with assertThat. ```java import static org.hamcrest.CoreMatchers.is; ``` ```java import static org.hamcrest.CoreMatchers.*; ``` -------------------------------- ### Create a Test Suite with Suite Runner Source: https://github.com/junit-team/junit4/wiki/Aggregating-tests-in-suites Annotate a class with `@RunWith(Suite.class)` and `@Suite.SuiteClasses` to define a test suite. The class itself remains empty. ```java import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ TestFeatureLogin.class, TestFeatureLogout.class, TestFeatureNavigate.class, TestFeatureUpdate.class }) public class FeatureTestSuite { // the class remains empty, // used only as a holder for the above annotations } ``` -------------------------------- ### Test Multiple Hamcrest Matchers with assertThat Source: https://github.com/junit-team/junit4/wiki/Assertions Demonstrates using `assertThat` with various Hamcrest core matchers like `equalTo`, `startsWith`, `not`, `anyOf`, and `sameInstance`. Requires Hamcrest CoreMatchers imports. ```java import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.anyOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertThat; import org.hamcrest.core.CombinableMatcher; // ... @Test public void testAssertThatHamcrestCoreMatchers() { assertThat("good", allOf(equalTo("good"), startsWith("good"))); assertThat("good", not(allOf(equalTo("bad"), equalTo("good")))); assertThat("good", anyOf(equalTo("bad"), equalTo("good"))); assertThat(7, not(CombinableMatcher. either(equalTo(3)).or(equalTo(4)))); assertThat(new Object(), not(sameInstance(new Object()))); } ``` -------------------------------- ### Deploy GPG Signed Snapshot Version with Maven Source: https://github.com/junit-team/junit4/blob/main/doc/building-junit.txt Use this command to deploy a GPG signed snapshot version of JUnit. Ensure your GPG keys and settings are configured correctly. ```bash $ ./mvnw -Pjunit-release clean deploy ``` -------------------------------- ### Specify Test Method Order with @FixMethodOrder Source: https://github.com/junit-team/junit4/wiki/Test-execution-order Use the `@FixMethodOrder` annotation to control test execution order. This example sorts methods lexicographically by name using `MethodSorters.NAME_ASCENDING`. ```java import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestMethodOrder { @Test public void testA() { System.out.println("first"); } @Test public void testB() { System.out.println("second"); } @Test public void testC() { System.out.println("third"); } } ``` -------------------------------- ### Basic JUnit 4 Test with Popper Source: https://github.com/junit-team/junit4/wiki/Theories Demonstrates the basic syntax of JUnit 4 tests using Popper's assertThat, which is based on Hamcrest. Ensure JUnit and Popper are on your classpath. ```java public class DollarTest { @Test public void multiplyByAnInteger() { assertThat(new Dollar(5).times(2).getAmount(), is(10)); } } ``` -------------------------------- ### Specify Test Method Order with @OrderWith Source: https://github.com/junit-team/junit4/wiki/Test-execution-order Use the `@OrderWith` annotation to specify a custom method execution order using an Ordering.Factory. This example uses `Alphanumeric.class` to sort methods by name. ```java import org.junit.Test; import org.junit.runner.OrderWith; import org.junit.runner.manipulation.Alphanumeric; @OrderWith(Alphanumeric.class) public class TestMethodOrder { @Test public void testA() { System.out.println("first"); } @Test public void testB() { System.out.println("second"); } @Test public void testC() { System.out.println("third"); } } ``` -------------------------------- ### Configure SBT for JUnit Categories Source: https://github.com/junit-team/junit4/wiki/Categories Shows how to specify JUnit categories for inclusion and exclusion using SBT's junit-interface via command-line arguments. ```bash --include-categories= --exclude-categories= ``` -------------------------------- ### Running JUnit Tests from Command Line Source: https://github.com/junit-team/junit4/blob/main/src/site/markdown/cookbook.md Execute tests from the command line, ensuring both the test class and JUnit are on the classpath. ```bash java org.junit.runner.JUnitCore TestClass1.class [...other test classes...] ``` -------------------------------- ### General assertThat Syntax Source: https://github.com/junit-team/junit4/wiki/Matchers-and-assertThat Illustrates the general structure of an assertThat statement, which involves a value and a matcher statement. ```java assertThat([value], [matcher statement]); ``` -------------------------------- ### Manage Class-Level Resources with ClassRule in Java Source: https://github.com/junit-team/junit4/wiki/Rules The ClassRule annotation allows static fields to act as Rules, affecting the entire test class. This example demonstrates connecting to a server before all tests run and disconnecting after. ```java @RunWith(Suite.class) @SuiteClasses({A.class, B.class, C.class}) public class UsesExternalResource { public static final Server myServer = new Server(); @ClassRule public static final ExternalResource resource = new ExternalResource() { @Override protected void before() throws Throwable { myServer.connect(); }; @Override protected void after() { myServer.disconnect(); }; }; } ``` -------------------------------- ### Apply Global Timeout with Timeout Rule in Java Source: https://github.com/junit-team/junit4/wiki/Rules The Timeout Rule can be applied at the class level to enforce a specific timeout for all test methods within that class. This example sets a timeout of 20 milliseconds. ```java public static class HasGlobalTimeout { public static String log; @Rule public final TestRule globalTimeout = Timeout.millis(20); @Test public void testInfiniteLoop1() { log += "ran1"; for(;;) } @Test public void testInfiniteLoop2() { log += "ran2"; for(;;) } } ``` -------------------------------- ### Run JUnit from Command Line Source: https://github.com/junit-team/junit4/wiki/FAQ Command to execute JUnit tests directly from the command line using the JUnitCore runner. Ensure your CLASSPATH is correctly set. ```java java org.junit.runner.JUnitCore ``` -------------------------------- ### Create Static Test Suite (Dynamic Invocation) Source: https://github.com/junit-team/junit4/blob/main/doc/testinfected/testing.htm Define a static suite method that returns a TestSuite. Tests are added dynamically by creating instances of MoneyTest with specific method names. This method is suitable for running a collection of tests. ```java public static Test suite() { TestSuite suite= new TestSuite(); suite.addTest(new MoneyTest("testEquals")); suite.addTest(new MoneyTest("testSimpleAdd")); return suite; } ``` -------------------------------- ### Deploy Specified Release and Next Development Version in Non-Interactive Mode Source: https://github.com/junit-team/junit4/blob/main/doc/building-junit.txt This command deploys a specified release version and sets the next development version in non-interactive mode. It's useful for automating release processes. ```bash $ ./mvnw -B -DreleaseVersion=4.12 -DdevelopmentVersion=4.13-SNAPSHOT release:prepare release:perform ``` -------------------------------- ### Cut a Release for Internal Use with Custom Repository and GPG Skip Source: https://github.com/junit-team/junit4/blob/main/doc/building-junit.txt This command is for cutting a release for internal organizational use. It allows skipping GPG signing and specifying a custom Maven repository for deployment. ```bash $ ./mvnw -DpushChanges=false -DlocalCheckout '-Darguments=-Dgpg.skip=true -DaltDeploymentRepository=my-company-repo-id::default::my-company-repo-url' -B -DreleaseVersion=4.12-mycompany-1 release:prepare release:perform ``` -------------------------------- ### Run JUnit 4 Tests from Command Line Source: https://github.com/junit-team/junit4/wiki/Test-runners Execute JUnit 4 tests from the command line using JUnitCore. Both test classes and JUnit must be on the classpath. ```java java org.junit.runner.JUnitCore TestClass1 [...other test classes...] ``` -------------------------------- ### Test Case for Simplification Source: https://github.com/junit-team/junit4/blob/main/doc/testinfected/testing.htm Verifies that a MoneyBag containing a single Money object after an addition is correctly simplified to a single Money object. ```java 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"))); } ``` -------------------------------- ### Create Dynamic Test Case Source: https://github.com/junit-team/junit4/blob/main/doc/testinfected/testing.htm Instantiate a TestCase by providing the test method name. This approach is compact but less type-safe, potentially leading to NoSuchMethodException at runtime. ```java TestCase test= new MoneyTest("testSimpleAdd"); ``` -------------------------------- ### JUnit 4 Test with TemporaryFolder and ExpectedException Rules Source: https://github.com/junit-team/junit4/wiki/Rules Demonstrates using TemporaryFolder to manage temporary files and ExpectedException to assert exceptions in a test class. Ensure necessary imports for JUnit annotations and assertions. ```java public class DigitalAssetManagerTest { @Rule public final TemporaryFolder tempFolder = new TemporaryFolder(); @Rule public final ExpectedException exception = ExpectedException.none(); @Test public void countsAssets() throws IOException { File icon = tempFolder.newFile("icon.png"); File assets = tempFolder.newFolder("assets"); createAssets(assets, 3); DigitalAssetManager dam = new DigitalAssetManager(icon, assets); assertEquals(3, dam.getAssetCount()); } private void createAssets(File assets, int numberOfAssets) throws IOException { for (int index = 0; index < numberOfAssets; index++) { File asset = new File(assets, String.format("asset-%d.mpg", index)); Assert.assertTrue("Asset couldn't be created.", asset.createNewFile()); } } @Test public void throwsIllegalArgumentExceptionIfIconIsNull() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Icon is null, not a file, or doesn't exist."); new DigitalAssetManager(null, null); } } ``` -------------------------------- ### JUnit 4 ExternalResource Rule for Resource Management Source: https://github.com/junit-team/junit4/wiki/Rules Shows how to use the ExternalResource rule to manage external resources like servers. The `before()` method sets up the resource, and `after()` tears it down, ensuring cleanup. ```java public static class UsesExternalResource { Server myServer = new Server(); @Rule public final 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); } } ``` -------------------------------- ### Run JUnit 4 Tests from Console Source: https://github.com/junit-team/junit4/wiki/FAQ Execute JUnit 4 tests directly from the command line using JUnitCore. Specify the fully qualified name of the test class. ```bash java org.junit.runner.JUnitCore junitfaq.SimpleTest ``` ```bash java junitfaq.SimpleTest ``` -------------------------------- ### Adapting JUnit 4 Tests for Older Runners Source: https://github.com/junit-team/junit4/blob/main/src/site/markdown/cookbook.md Declare a static suite() method returning a Test using JUnit4TestAdapter to make JUnit 4 tests accessible to older JUnit runners. ```java public static junit.framework.Test suite() { return new JUnit4TestAdapter(Example.class); } ``` -------------------------------- ### JUnit Build Machine Maven Settings Source: https://github.com/junit-team/junit4/blob/main/doc/building-junit.txt This is an internal template of the Maven settings.xml file used by the JUnit build machine. It configures server credentials and GPG properties for releases. ```xml central-portal junit-release ... false true /private/.../.gnupg /private/.../.gnupg/pubring.gpg /private/.../.gnupg/secring.gpg ``` -------------------------------- ### Cut a Release of the Current Target Version with Maven Source: https://github.com/junit-team/junit4/blob/main/doc/building-junit.txt This command prepares and performs a release of the current target version in pom.xml. It removes '-SNAPSHOT', cuts the release, increments the version, and adds '-SNAPSHOT' back. ```bash $ ./mvnw -B release:prepare release:perform ``` -------------------------------- ### Order Test Rules with RuleChain Source: https://github.com/junit-team/junit4/wiki/Rules Use RuleChain to specify the order in which TestRules are applied. Rules are applied from outer to inner. ```java public static class UseRuleChain { @org.junit.Rule public final org.junit.rules.TestRule chain = org.junit.rules.RuleChain .outerRule(new LoggingRule("outer rule")) .around(new LoggingRule("middle rule")) .around(new LoggingRule("inner rule")); @org.junit.Test public void example() { assertTrue(true); } } ``` -------------------------------- ### Cut a Release While Changing the Target Version with Maven Source: https://github.com/junit-team/junit4/blob/main/doc/building-junit.txt Use this command to specify a release version different from the current pom.xml version. It prepares and performs the release, then increments the specified version and adds '-SNAPSHOT'. ```bash $ ./mvnw -B -DreleaseVersion=5.0 release:prepare release:perform ``` -------------------------------- ### Configure JUnit 4.10 and Earlier Dependencies Source: https://github.com/junit-team/junit4/wiki/Use-with-Gradle For JUnit 4.10 and earlier, explicitly declare Hamcrest core and library dependencies before junit-dep. This configuration also includes Mockito. ```groovy dependencies { testCompile group: 'org.hamcrest', name: 'hamcrest-core', version: '1.3' testCompile group: 'junit', name: 'junit-dep', version: '4.10' testCompile group: 'org.hamcrest', name: 'hamcrest-library', version: '1.3' testCompile group: 'org.mockito', name: 'mockito-core', version: '1.9.+' } ``` -------------------------------- ### Rebase and Reapply Changes After Merging Master Source: https://github.com/junit-team/junit4/wiki/Pull-Requests If you have merged from master or are unsure, create a new branch and reapply your changes. This method safely combines your work with the latest master. A descriptive commit message is required. ```bash git checkout your-branch git merge master git branch -m your-branch your-branch-orig git checkout -b your-branch master git read-tree -u -m your-branch-orig git commit ``` -------------------------------- ### Test String Equality with assertEquals Source: https://github.com/junit-team/junit4/wiki/Assertions Use `assertEquals` to compare two strings for equality. The first parameter is an optional failure message. ```java import static org.junit.Assert.assertEquals; // ... @Test public void testAssertEquals() { assertEquals("failure - strings are not equal", "text", "text"); } ``` -------------------------------- ### TestCase.run() Methods Source: https://github.com/junit-team/junit4/blob/main/doc/cookstour/cookstour.htm The `run` methods in the TestCase class, responsible for executing tests and collecting results. ```APIDOC ## TestCase.run() Methods ### Description These methods execute a test case and collect its results using a `TestResult` object. The no-parameter `run()` method creates its own `TestResult`. ### Method `public TestResult run()` `protected void run(TestResult result)` ### Endpoint N/A (These are class methods, not API endpoints) ### Parameters #### `run()` No parameters. #### `run(TestResult result)` - **result** (TestResult) - Required - The `TestResult` object to collect outcomes. ### Request Example ```java // Example of calling the no-parameter run method TestCase myTest = new MyTestCase(); TestResult results = myTest.run(); // Example of calling the run method with a TestResult TestResult existingResult = new TestResult(); myTest.run(existingResult); ``` ### Response #### Success Response (200) - **TestResult** (TestResult) - An object containing the results of the test execution. #### Response Example ```json { "run()": { "testCount": 1, "failureCount": 0, "errorCount": 0 } } ``` ``` -------------------------------- ### Maven Dependencies for JUnit 4.10 and Earlier with Hamcrest Source: https://github.com/junit-team/junit4/wiki/Use-with-Maven For JUnit 4.10 and earlier, declare junit-dep and explicitly manage the hamcrest-core and hamcrest-library dependencies to use the full Hamcrest matcher library. Mockito is also included. ```xml org.hamcrest hamcrest-core 1.3 test junit junit-dep 4.10 test org.hamcrest hamcrest-library 1.3 test org.mockito mockito-core 1.9.0 test ``` -------------------------------- ### Apply Custom TestLogger Rule in a Test Source: https://github.com/junit-team/junit4/wiki/Rules Demonstrates how to apply the custom TestLogger rule in a test class and access the logger instance. ```java import java.util.logging.Logger; import org.example.junit.TestLogger; import org.junit.Rule; import org.junit.Test; public class MyLoggerTest { @Rule public final TestLogger logger = new TestLogger(); @Test public void checkOutMyLogger() { final Logger log = logger.getLogger(); log.warn("Your test is showing!"); } } ``` -------------------------------- ### assertThat with AnyOf Matcher Source: https://github.com/junit-team/junit4/wiki/Matchers-and-assertthat-CN Shows how to use assertThat with the anyOf matcher to assert that a string contains either of the specified substrings. This provides a more readable failure message compared to traditional OR logic. ```java assertThat(responseString, anyOf(containsString("color"), containsString("colour"))); ``` -------------------------------- ### Discover Slowest Tests from Surefire XML Output Source: https://github.com/junit-team/junit4/wiki/Use-with-Maven This bash command processes Surefire XML reports to identify and list the slowest test cases, sorted from slowest to fastest. It requires `grep`, `find`, `sed`, `sort`, and `head` utilities. ```bash grep -h "