Nepo Znat
Nepo Znat

Reputation: 3270

Testing with manual calculation or programmed calculation?

I'm using Django and I need to write a test that requires calculation. Is it best practice to calculate the expected value manually or is it ok to do this by using the sum function (see below)

This example is easier for me because I don't have to calculate something manually:

def test_balance(self):
    amounts = [120.82, 90.23, 89.32, 193.92]
    for amount in amounts:
        self.mockedTransaction(amount=amount)
    total = Balance.total()

    self.assertEqual(total, sum(amounts))

Or in this example I have to calculate the expected value manually:

def test_balance(self):
    self.mockedTransaction(amount=120.82)
    self.mockedTransaction(amount=90.23)
    self.mockedTransaction(amount=89.32)
    self.mockedTransaction(amount=193.92)
    total = Balance.total()

    self.assertEqual(total, 494.29)

Upvotes: 0

Views: 68

Answers (1)

Bill the Lizard
Bill the Lizard

Reputation: 405795

Does your total function just use sum to get the sum of a list of numbers? If so, your test is performing the same steps as your code under test. In that case, the first test can't fail. It would be better to use a manually generated value. (If total does just wrap sum, then I wouldn't spend a lot of time worrying about it, though. That function has been thoroughly tested.)

If Balance.total() is getting its value by some other method (like a SQL query run on the database), then it's fine to compute the expected value in your test method, particularly in simple cases like summing a list of values. If the computation is very complex, then you probably want to go back to manually calculated values. Otherwise your test code might be just as difficult to debug as your code under test.

Upvotes: 1

Related Questions