הלינקייה: מגזין חודשי למפתחים

רוצה לשמוע על כל האירועים, המדריכים, הקורסים והמאמרים שנכתבו החודש ?
הלינקייה הינו מגזין חופשי בעברית שמשאיר אותך בעניינים.
בלי ספאם. בלי שטויות. פעם בחודש אצלך בתיבה.

JUnit Example

Below is the Summer class example and its JUnit test case.
The Summer class accumulates numbers using the add method, and provides a calcSum() method to calculate the total sum of all the numbers accumulated so far. It is simple enough for our example here.
JUnit is a great tool for testing a class behaves as it should. Using JUnit, we write common use cases for the class, and the expected result using assertions. JUnit automatically runs those tests and checks if the results were as expected. When they are, we get the green line, when they're not - we get the red. This way, there's no need to remember what is the right answer, and so we minimize our chances to err.

Note how the test class is divided to three sections, each JUnit test section is a method starting with the word test. This is mandatory.
Inside the method, we can write anything. In the following example, three types of usages are tested, each with its own test method. Inside each test case, an assertion is made about the expected result. When the JUnit is performed, the assertion is tested and yields success or failure.

/**
 * The Summer class sums up integers. 
 * @author ynonperek
 *
 */
public class Summer {
	int total;
 
	/**
	 * Adds an integer to this object's sum
	 * @param number
	 */
	public void add(int number) {
		this.total += number;
	}
 
	/**
	 * Returns the sum of all the integers added so far
	 */
	public int calcSum() {
		return this.total;
	}
}
import junit.framework.Assert;
import junit.framework.TestCase;
 
 
public class Sumtester extends TestCase {
 
	/**
	 * Verifies positive numbers additions. 
	 * 10 + 20 + 30 = 60
	 */
	public void testPositiveNumbers() {
		Summer s = new Summer();
		s.add(10);
		s.add(20);
		s.add(30);
 
		Assert.assertEquals(60, s.calcSum());
	}
 
	/**
	 * Verifies negative numbers additions
	 * (-10) + (-20) + (-30) = -60
	 */
	public void testNegativeNumbers() {
		Summer s = new Summer();
		s.add(-10);
		s.add(-20);
		s.add(-30);
 
		Assert.assertEquals(-60, s.calcSum());
	}
 
	/**
	 * Verifies initial value
	 */
	public void testZeros() {
		Summer s = new Summer();
		Assert.assertEquals(0, s.calcSum());
	}
}
course: