Over a million developers have joined DZone.

A Junit Introduction

DZone's Guide to

A Junit Introduction

· DevOps Zone ·
Free Resource

Discover a centralized approach to monitor your virtual infrastructure, on-premise IT environment, and cloud infrastructure – all on a single platform.

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);

Learn how to auto-discover your containers and monitor their performance, capture Docker host and container metrics to allocate host resources, and provision containers.


Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}