Over a million developers have joined DZone.

A Junit Introduction

DZone's Guide to

A Junit Introduction

· DevOps Zone ·
Free Resource

DevOps involves integrating development, testing, deployment and release cycles into a collaborative process. Learn more about the 4 steps to an effective DevSecOps infrastructure.

Junit framework is a unit testing framework for Java Programming language. Most developers feel that if I am good programmer then I don't need to test. But unit testing is very much a developer's responsibility. Many developers might feel writing code for unit testing is time consuming and it requires a new language to be learnt then not many would even write such a code.

But with JUnit it is our very own java language -and it is quick to execute. Maintenance of code becomes easy since the tests are automated and once developed with the advent of fast computers it gives a sense of emotional satisfaction that no other code has been affected.

JUnit fixture object

in older versions of Junit fixture is inherited from junit.framework.TestCase. But with Junit 4 we should use @Before @After @Test annotations.  you can refactor setUp() and tearDown() in your code. it will be called once for each test method run.

Consider test class with 2 test methods in it to test java's inbuild object ArrayList. If the array is empty it should print 0 - if it has 1 element it should print 1. Each test works with it's own copy of object created by setUp() and tearDown() although we have not used it in this example;

import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.*;
public class first {
List fixture = new ArrayList();
public void setUp() throws Exception {
public void tearDown() throws Exception {
public void testA() {
assertTrue(fixture.size() == 0);
public void testB() {
Object element = new Object();
assertTrue(fixture.size() == 1);

Read the 4-part DevOps testing eBook to learn how to detect problems earlier in your DevOps testing processes.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}