mercredi 24 février 2016

Could you explain Test Driven Development using my specific example?

I am trying to understand Test Driven Development, but still do not get it.

Let's imagine, that we need to write a function, that returns power of a number.

def power_of_a_number ( number, power ):
.... <some code here>...

According to TDD, we need to write a test first. How do we write the test?

Well, I know, that 2^2 = 4.

So I expect the function to return "4" if we pass "2" and "2" as parameters to it.

OK, I write the test:

if power_of_a_number ( 2, 2 ) == 4:
    print ( "The test is passed" )

After that test the function looks simple:

def power_of_a_number ( number, power ):
    return 4

Whooo, the test is passed! The function is written!

But I did not achieve the results - the function I have written is still crap.

So, I can extend the test. What else do I know? Well, 3^4 = 81. OK, let's extend the test!

if power_of_a_number ( 2, 2 ) == 4 and power_of_a_number ( 3, 4 ) == 81:
    print ( "The test is passed" )

Brilliant. Now the function looks much more advanced:

def power_of_a_number ( number, power ):
    if number == 2 and power == 2:
        return 4
    if number == 3 and power == 4:
        return 81

Once again the tests are passed! And once again the function is incomplete.

Well, we can add 5^2 = 25.

if power_of_a_number ( 2, 2 ) == 4 and power_of_a_number ( 3, 4 ) == 81 and power_of_a_number ( 5, 2 ) == 25:
    print ( "The test is passed" )

...

def power_of_a_number ( number, power ):
    if number == 2 and power == 2:
        return 4
    if number == 3 and power == 4:
        return 81
    if number == 5 and power == 2:
        return 25

And this way we can continue on and on...

What am I missing in this structure? What can formally be done according to TDD (!) to write the right test and to write the right code?

Thank you!

Aucun commentaire:

Enregistrer un commentaire