Skip to main content

Section 2.6 JUint Example

Let us assume that we have a single class, Calculator, in a class library project. Add looks pretty reliable at first glance, but so does all the code you write. You still need to test it, if only to prove your rightness to others.
public class Calculator{
public int Add(int x, int y){
return x + y;
}
}
Traditionally, we write a console class or main method inside the class, for example,
class CalculatorTest {
static void Main(string[] args){
Calculator calculator = new Calculator();
int result = calculator.Add(5, 6);
if (result != 11)
throw new InvalidOperationException();
}
}
By using Junit package, we could have:
class CalculatorTest{
public void testAdd(){
Calculator calculator = new Calculator();
assertTrue(11 == calculator.Add(5, 6));
}
}
Note:
  • The key part here is writing a failing test first.
  • Remember that it is our objective to work in small steps to make sure we will never experience a sudden and unexpected test success or test failure. In practice, most developers take increasingly bigger steps, with the result of frequent surprises when they run their tests. That’s where we will hopefully distinguish ourselves as test-first masters by making giant steps when moving in well-known territory and making very tiny forward and sideward steps in unknown terrain and on slippery ground. However, this strategy requires that we know how to make the tiny steps in the first place.
  • At the beginning of each step, there was a test which was directly or indirectly motivated by the requirements specification. To be able to write this test, we had to make decisions about the public interface desired for our OUT (object under test). This public interface served both to “stimulate” the test object and to verify the correct behavior.
  • This approach drove and controlled the development of our production code from the tests.
  • So far, our tests have concentrated exclusively on the externally visible behavior of the OUT. In Java this theoretically includes all methods (and variables) with public, protected, or package scope visibility. In practice we restrict ourselves to use only what is intended to be used from the outside, that is from client code, which usually leaves out protected methods and members available for subclassing.
You have attempted of activities on this page.