DevOps Zone is brought to you in partnership with:

Adarsh has posted 1 posts at DZone. View Full User Profile

A Junit Introduction

08.09.2013
| 4347 views |
  • submit to reddit

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();
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testA() {
assertTrue(fixture.size() == 0);
System.out.println(fixture.size());
}
@Test
public void testB() {
Object element = new Object();
fixture.add(element);
assertTrue(fixture.size() == 1);
System.out.println(fixture.size());
}
}



Published at DZone with permission of its author, Adarsh Lr.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Raging Infernoz replied on Wed, 2013/08/14 - 8:28am

JUnit is obsolete; TestNG is much better.


Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.