📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
1. What is 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
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
- 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.
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());
}
}
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
- 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.
@Test
public void whenAssertingEquality_thenEqual() {
String expected = "Ramesh";
String actual = "Ramesh";
assertEquals(expected, actual);
}
6. Real-World Example using JUnit Framework
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
new ArrayList<Object>().get(0);
@Test(expected= IndexOutOfBoundsException.class)
public void empty() {
new ArrayList<Object>().get(0);
}
Comments
Post a Comment
Leave Comment