Skip to content

Basic Unit Test Tutorial

Josh edited this page Jan 30, 2015 · 7 revisions

Here's a link to a fairly good tutorial that helped me out:http://www.vogella.com/tutorials/JUnit/article.html

If you want a quick cheatsheet for JUnit syntax, just check out the cheatsheet page.

Here's a basic JUnit class I created to show how JUnit works:

package tests;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author Warren
 */


//This class is just an example to show you how JUnit works.

//Essentially, you will have functions which will be tests, which will be prefixed with @Test. In them, 
//you will use assert() statements to check certain parts of your system. If an assert fails or you use
//fail(), the test will fail. If this doesn't happen, the test will be marked as a success.


public class TestTester {

public TestTester() 
{
}

private static int testCount=0;

//Use @BeforeClass for stuff you want to run once before all the tests start. This includes things like
//database connections.

@BeforeClass
public static void setUpClass() 
{ 

}

//Use @AfterClass for stuff you want to run once after all the tests end. This includes stuff like
//closing database connections, and other clean-up operations.

@AfterClass
public static void tearDownClass() 
{

}

//Use @Before for things you want to run before every single test. This can cover setting up all the
//objects you need for the tests, or reseting them to a certain state.

@Before
public void setUp() 
{
    testCount=testCount+1;
    System.out.println("Starting Test "+testCount);
}

//Use @After for things you want to run after every single test. You can use this to reset the items
//to a base state.

@After
public void tearDown() 
{
    System.out.println("Finishing Test "+testCount);
}

// All tests are prefixed with @Test, which marks them as a test to be run when you run this a test file.
// The basic type of test fails if an assertion fails, or if use fail(String), which contains an error 
// message.

@Test
public void daTest()//This test will fail on the second statement
{
    assertEquals("Arithmetic doesn't work properly",0,(4-4));
    assertEquals("This should fail",0,(7-6));//This will cause this test to fail.
}

@Test
public void anotherTest()//This will pass.
{
    assertEquals("This should pass!", 0,0);
}

// TODO add test methods here.
// The methods must be annotated with annotation @Test. For example:
//
// @Test
// public void hello() {}
}

Clone this wiki locally