JUnit is a unit testing framework for Java that allows developers to write and run repeatable automated tests to determine whether changes introduce bugs. Key features include annotations to identify test methods, assertions to validate expected results, and test runners to execute tests. Tests are organized into classes following conventions like naming test classes with "Test" and methods with "test". JUnit provides components like fixtures, assertions, test suites, and rules to structure tests. It supports various testing scenarios including parameterized, ignored, timed, and exception tests.
2. What is JUnit ?
• JUnit is a Regression Testing Framework* for
the Java Programming Language.
• One of a family of unit testing frameworks
collectively known as xUnit.
• Open source framework
*One of the main reasons for regression testing is to
determine whether a change in one part of the
software affects other parts of the software
3. Features
• Provides Annotation to identify the test
methods.
• Provides Assertions for testing expected results.
• Provides Test runners for running tests.
4. Coding Conventions
o Name of the test class end with "Test".
o Name of the method begin with "test".
o Return type of a test method must be void.
o Test method must not throw any exception.
o Test method must not have any parameter.
4
5. Simple Test
public class FooTest {
@Test
public void testMultiply() {
MyClass tester = new MyClass();
// Tests
assertEquals("10 x 0 must be 0", 0, tester.multiply(10, 0));
assertEquals("0 x 10 must be 0", 0, tester.multiply(0, 10));
assertEquals("0 x 0 must be 0", 0, tester.multiply(0, 0));
}
}
6. Component of JUnit
• JUnit test framework provides following
important features/component
oFixtures
oAssertions (provides Assert API)
oTest suites (TestSuite API)
oJUnit classes
7. Fixtures
• Fixtures is a fixed state of a set of objects used as a
baseline for running tests. The purpose of a test fixture is
to ensure that there is a well known and fixed
environment in which tests are run so that results are
repeatable.
- Usage -
o Preparation of input data and setup/creation of fake or
mock objects
o Loading a database with a specific, known set of data
o Copying a specific known set of files creating a test
fixture will create a set of objects initialized to certain
states.
7
9. Assert
public class Assert extends java.lang.Object
• This class provides a set of assertion methods useful for
writing tests. Only failed assertions are recorded.
• JUnit provides overloaded assertion methods for all
primitive types and Objects and arrays (of primitives or
Objects)
• If fail AssertionFailedError
11. Test Suite
• Test suite means bundle a few unit test cases
and run it together. In JUnit,
both @RunWith and @Suite annotation are
used to run the suite test.
11
12. TestSuite Example
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
}
13. Test execution order
• JUnit does not specify the execution order of test method
invocations
• From version 4.11, JUnit will by default use a deterministic,
but not predictable, order (MethodSorters.DEFAULT)
• @FixMethodOrder(MethoSorters.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.
15. Ignore Test
• Sometimes it happens that our code is not ready
and test case written to test that method/code
will fail if run or we just don’t want to test that
test case at that moment.
The @Ignore annotation helps in this regards.
oA test method annotated with @Ignore will not
be executed.
oIf a test class is annotated with @Ignore then all
of its test methods will be ignored.
16. Ignored Test Example
import org.junit.Ignore;
import org.junit.Test;
@Ignore
public class IgnoreTest {
@Test
public void notIgnored()
{
System.out.println("this is executed");
}
@Ignore
@Test
public void itIsIgnored()
{
System.out.println("This test is ignored");
}
}
17. Time test
• Junit provides a handy option of Timeout. If a
test case takes more time than specified number
of milliseconds then Junit will automatically
mark it as failed. The timeout parameter is
used along with @Test annotation.
18. Time Test xample
import org.junit.Test;
public class TimeTest {
@Test(timeout=10)
public void testTime()
{
for(int i=0;i<1000;i++){
System.out.println("hiiiiii");
}
}
}
19. Exception Test
• Junit provides a option of tracing the Exception
handling of code. You can test the code whether
code throws desired exception or not.
The expected parameter is used along with
@Test annotation.
20. Exception Test Example
import org.junit.Test;
public class ExceptionTest {
@Test(expected=ArithmeticException.class)
public void exception() {
int s=12/0;
}
}
21. Parameterized Test
• Junit 4 has introduced a new feature Parameterized
tests.Parameterized tests allow developer to run the
same test over and over again using different values.
There are five steps, that you need to follow to
create Parameterized tests.
o Annotate test class with @RunWith(Parameterized.class)
o Create a public static method annotated with @Parameters that
returns a Collection of Objects (as Array) as test data set.
o Create a public constructor that takes in what is equivalent to one
"row" of test data.
o Create an instance variable for each "column" of test data.
o Create your tests case(s) using the instance variables as the source
of the test data.
23. Rules
• Via the @Rule annotation you can create objects
which can be used and configured in your test
methods.
• This adds more flexibility to your tests.
• Testers can reuse or extend one of the provided
Rules ,or write their own.
25. More Rules
TemporaryFolder 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):
Timeout The Timeout Rule applies the same timeout to all test
methods in a class
TestName The TestName Rule makes the current test name
available inside test methods
ErrorCollector 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):
ExpectedException The ExpectedException Rule allows in-test
specification of expected exception types and
messages:
26. 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