JUnit tutorial for beginners and professionals with examples in eclipse on Basics, Test Framework, Basic usage, Writing Tests, Annotations, Executing Tests, Suite Test, Ignore Test, Time Test, Exceptions Test, Parameterized Test, Using Assertion, Plug with Ant, Plug with Eclipse and more.
Testing:
Testing is the process of checking an application that it is working as expected. Working as expected means for a known input it must give the expected output. In other words testing is a process of verification and validation.
Unit testing:
Unit testing is the testing of an individual unit (class/method) or group of related units.
Types of unit testing:
1. Manual testing
2. Automated testing
Manual testing:
Manual testing is the process of executing a test case without any tool support.
Automated testing:
Automated testing is the process of executing a test case with any tool support.
JUnit:
JUnit is an open-source unit testing framework for java programmers. It is only used for unit testing. Integration testing is done by TestNG.
Unit test case:
Unit test case is part of code which executes to check that another part of the code works as expected.
Note: We have to write two test cases for every requirement/sub-requirement one positive and one negative.
Annotations for Junit testing:
1. @Test: It is used to specify the test method.
2. @BeforeClass: It is used to specify that method will be called only once, before starting all the test cases.
3. @AfterClass: It is used to specify that method will be called only once, after finishing all the test cases.
4. @Before: It is used to specify that method will be called before each test case.
5. @After: It is used to specify that method will be called after each test case.
6. @Ignore: It is used to ignore the test case.
Assert class:
JUnit provides the Assert class to check the certain conditions. Assert class methods compare the output value to the expected value.
Commonly used methods of Assert class:
1. assertTrue(boolean condition): It assert that the specified boolean condition is true.
2. assertFalse(boolean condition): It assert that the specified boolean condition is false.
3. assertNull(Object obj): It assert that the specified object is null.
4. assertNotNull(Object obj): It assert that the specified object is not null.
5. assertEquals(Object expected, Object actual): It assert that two objects are equal.
6. assertSame(Object expected, Object actual): It assert that two objects refer to the same object.
Java JUnit tutorial:
- Junit basic annotation example.
- JUnit expected exception test.
- Junit ignore test.
- JUnit time test.
- JUnit suite test.
- JUnit parameterized test.
- Junit test runner.
JUnit interview questions: