From: Source
If you are too lazy to look at those long examples, you may wish to look at the following small example. This example will give you an intuitive understanding of test-driven development.
At least let you know That test-driven development is a development technology, not a testing technology.
A lot of people may have forgotten how to compile the Fibonacci series. It just shows you the power of tdd.
Test-driven development is inevitable.
The first test came.
Public void testFibonacci () // do not think this is junit. nunit can also be written like this, rather than using attributes. Do not believe it.
{
AssertEquals (0, Fib (0 ));
}
The first number of the Fibonacci series is 0. Everyone knows it. Now that the test code is available, run the test first.
Failed, error reported, hateful red progress bar.
Obviously, we don't even have the Fib () function yet.
So let's get this test passed.
Int Fib (int n)
{
Return 0;
}
OK !!! Green, which is your favorite color in tdd (it is good for us to see more green)
Second test
Public void testFibonacci ()
{
AssertEquals (0, Fib (0 ));
AssertEquals (1, Fib (1 ));
}
Let's make it pass.
Int Fib (int n)
{
If (n = 0) return 0;
Return 1;
}
Passed!
From the test code, we can see that
AssertEquals (0, Fib (0 ));
AssertEquals (1, Fib (1 ));
Repeat! We should avoid repetition not only in the source code, but also in the test code !! (The mode will also appear in the test code ~~)
Here, we use the simplest method to avoid duplication and use the table driver.
We started to rewrite the test code.
Public void testFibonacci
{
Int cases [] [] = {0, 0 }};
For (int I = 0; I <case. Length; I ++)
AssertEquals (case [I] [1], fib [I] [0]);
}
In this way, it is much easier to add the test code.
The test code has been changed !!! Be careful. Let's run it again. We can continue with it with confidence.
Public void testFibonacci
{
Int cases [] [] = {0, 0 }};
For (int I = 0; I <case. Length; I ++)
AssertEquals (case [I] [1], fib [I] [0]);
}
Oh! Failed. Solve it quickly
Int Fib (int n)
{
If (n = 0) return 0;
If (n <= 2) return 1;
Return 2;
}
Oh, %