JUnit Tutorials

JUnit is a annotation-based, flexible unit testing framework for the Java Programming Language. JUnit has been important in the development of test-driven development and is one of a family of unit testing frameworks which is collectively known as xUnit. Here are some examples and tutorials to get you started in learning JUnit.

Getting Started

Some tutorials to get you started.

  • Basic JUnit test

    Testing is critical for building good quality software. We will show you the basics of writing a JUnit Test.

JUnit Tutorials

Other JUnit tutorials that help you learn the basics.

  • Test Suite

    Using Suite as a runner allows you to build a suite containing tests. To create a suite, annotate a class with @RunWith(Suite.class). To add test classes to that suite, annotate the same class and add @SuiteClasses(TestClass.class, …).

  • Ignoring a Test

    You can Ignore a test either by annotating it with a @Ignore or by deleting the @Test annotation, But the test runner will not report such a test. Better is to use the @Ignore annotation at method or class level.

  • Timeouts

    You can specify a timeout in JUnit, this means that when a test execution is longer than the specified timeout the test method will fail automatically and be marked as a failure. There are two ways to implement a timeout using JUnit.

  • Exception Testing

    JUnit provides us with a basic toolkit to verify if an exception is thrown. There are some differences in how we can check these exceptions.

  • Assumptions with Assume

    We can defend our tests by using the org.junit.Assume class. This class offers many static methods, such as assumeTrue(condition) or assumeNotNull(condition) and etc.

  • Implement JUnit listener

    A JUnit Listener can listen to events of JUnit lifecycle. We can add this listener by creating a custom Runner. Then we use this runner with the @RunWith annotation which will register our JUnit Listener to the test case.

  • Parameterized Test

    The Parameterized test runner allows you to run a test many times with different sets of parameters. To run a test class with the Parameterized test runner, you must meet the following requirements.

  • Theories

    A theory captures some aspect of the intended behavior in possibly infinite numbers of potential scenarios. This means whatever a theory asserts is expected to be true for all data sets.

  • Ordered Tests

    The JVM does not specify any particular order and could be random. Normally this should not be a problem, cause well written tests would not assume any order, but some do.

  • Custom Method Order

    By default JUnit does not support to run JUnit tests in method order. JUnit only provides to run ordered method execution by name ascending NAME_ASCENDING or descending JVM.

References