In this article, we will quickly have an introduction and overview of the JUnit Framework.
In Junit4 there is no setup() or tearDown() method and instead of that we have @Before and @After annotations. By using @Before you can make any method as setup() and by using @After you can make any method as teardown().
1. What is JUnit?
JUnit is a unit testing framework for Java programming language. JUnit has been important in the development of test-driven development, and is one of a family of unit testing frameworks collectively known as xUnit, that originated with JUnit.
- Assertions for testing expected results
- Test fixtures for sharing common test data
- Test runners for running tests JUnit were originally written by Erich Gamma and Kent Beck.
2. Benefits of using JUnit
- JUnit is a testing framework that developers use for writing test cases while developing the software. They would write and run test cases for every function they write. So using this, you make sure that every single line of code will be tested.
- Every time you make a small or a big modification in the code (in any function), you can make sure that the function is performing well and has not broken any older functionality by executing all JUnit test cases in one go written for that function. So, you write a test case once, and go on using the test case, again and again, to make sure that- every time software is modified it is working as expected!
- Using JUnit, you can easily create and most importantly manage a rich unit test case suite for the entire software.
- Any new member in the team can easily understand the test cases written and managed using JUnit and consequently contribute towards writing more test cases for developing robust software.
- JUnit has become a standard for testing in Java programming language and is supported by almost all IDE’s e.g Netbeans, Eclipse etc. So, you work in any standardized IDE environment, you would find the support of JUnit in it.
3. JUnit Simple Basic Template
The following templates are a good starting point. Copy/paste and edit these templates to suit your coding style.
Here is a SampleTest class which represents a basic test template:
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);
}
}
4. Fixture
A test fixture 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. Examples of fixtures:
- Preparation of input data and setup/creation of fake or mock objects
- Loading a database with a specific, known set of data
- Copying a specific known set of files creating a test fixture will create a set of objects initialized to certain states.
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:
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()
Learn more about test fixtures at JUnit 4 Test Fixtures Examples
5. Create Simple JUnit Test Case
Let's quickly take a look at how to create a very simple JUnit test and here are the steps:
- Create a method and annotate a method with @org.junit.Test
- Use assertEquals assertion which verifies that the expected and the actual values are equal.
- Run test using IDE or command line or if the project maven using mvn test command.
The assertEquals assertion verifies that the expected and the actual values are equal:
@Test
public void whenAssertingEquality_thenEqual() {
String expected = "Ramesh";
String actual = "Ramesh";
assertEquals(expected, actual);
}
6. Real-World Example using JUnit Framework
Let's understand a little bit more about using JUnit tests in a real-world example.
Consider we have a School Management System application and we want to write a sample test cases for the School entity.
In this example, we will see the sample CRUD JUnit test cases for the School entity:
public class SchoolServiceImplTest {
private SchoolService schoolService;
/**
* This method initialize all domain objects required for test methods.
*/
@Before
public final void setUp() throws Exception {
// Instantiates a School instance;
school = new School();
school.setName("BVB School");
school.setAddress("BVB School");
school.setContactNo("0778563251");
school.setFaxNo("0778563251");
school.setWebsite("javaguides.new");
school.setStartedDate(date);
school.setModifiedTime(date);
}
@Test
public final void testAddSchool() throws Exception {
School newSchool = schoolService.addSchool(school);
assertNotNull("School Type object should not null ", newSchool);
}
@Test
public final void testUpdateSchool() {
School newSchool = schoolService.addSchool(school);
assertNotNull(newSchool);
newSchool.setContactNo("0145785545");
schoolService.updateSchool(newSchool);
}
@Test
public final void testFindSchool() throws AkuraAppException {
School newSchool = schoolService.addSchool(school);
assertNotNull(newSchool);
School findSchool = schoolService.findSchool(
newSchool.getSchoolId());
assertNotNull("School Type object should not null ", findSchool);
}
@Test
public final void testGetSchoolList() throws AkuraAppException {
School newSchool = schoolService.addSchool(school);
assertNotNull(newSchool);
List<School> schoolList = schoolService.getSchoolList();
}
@After
public final void teardown() throws SchoolNotFoundException {
schoolDao.delete(school);
}
}
7. 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);
}
8. Conclusion
In this post, we have discussed what is JUnit framework, it's benefits, basic template, fixture, and sample examples.
Going forward, we will learn everything about how to use the JUnit framework in Java with examples.
Comments
Post a Comment
Leave Comment