alexcuesta

My tech blog

JUnit with parameters

leave a comment »

Today I have to implement some tests to calculate the total gross price and vat amounts of an order.
As I had some examples from the product owner, I decided to unit test the Order class using the parameters feature provided in JUnit 4.

This is an easy example of how to do it testing the add operation of a calculator:

@RunWith(Parameterized.class)
public class AddTest {

	private int operator1;
	private int operator2;
	private int expectedTotal;
	
	// this creates a new test per example provided in the method tagged with @Parameters
	public AddTest(int operator1, int operator2, int expectedTotal) {
		this.operator1 = operator1;
		this.operator2 = operator2;
		this.expectedTotal = expectedTotal;
	}

	// Given Examples
	@Parameters
	public static Collection data() {
		return Arrays.asList( new Object[][] {
				{1, 1, 2},      // 1 + 1 should be 2
				{1, -1, 0},    // 1 - 1 should be 0
				{1, -2, -1}    // 1 -2 should be -1
		});
	}	
	
	// The actual test
	@Test
	public void shouldAdd() throws Exception {
		//given
		Calculator calculator = new Calculator();
		calculator.enterOperator(operator1);
		calculator.enterOperator(operator2);

		//when
		int actualTotal = calculator.add();
		
		//then
		assertThat(actualTotal, is(expectedTotal));
	}
}

Written by alexcuesta

October 12, 2010 at 3:44 pm

Posted in Java

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: