Unit Testing In Java – JUnit

I’m only going to quickly touch base on how to preform unit testing in Java.  Lars Vogel did a article on JUnit testing and provides screen captures on installing JUnit in eclipse.  Also JUnit comes bundle with Netbeans so if you already have this IDE installed you can start unit testing away.

Here is the link to the article: http://www.vogella.de/articles/JUnit/article.html

Here the production code I’m going to make a test.

package Source;

public class ProductionCode {
    private int x, y;

    public ProductionCode(int x, int y){
        this.x = x;
        this.y = y;

    public int add() { return( this.x + this.y ); }

Here is my unit test:

package Tester;

import Source.ProductionCode;
import org.junit.*;
import static org.junit.Assert.*;
public class JUnitTest {
    private ProductionCode pc;

    public JUnitTest() {
        this.pc = new ProductionCode(2,3);

    public void passAdd() { assertEquals( "Result", 5, this.pc.add() ); }

    public void failAdd() { assertEquals( "Result", 42, this.pc.add() ); }

If you run this test the unit test passAdd() will pass since 2 + 3 = 5 and the test failAdd() will fail since 2 + 3 != 42.  In the Netbeans IDE, you can press ctrl+F6 to start the test or do a right click and select Test File.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s