I am new to unittesting in python and this is my first unit test. I don't know whether I am doing right or wrong unit test , need some help. I have to test function, in first function i want to test legal deposit and in second function I want to test illegal deposit, like depositing "apple" or "lizard" instead of amount . Since I am new to unit test, I have lot of confusion about it. I read different post,but in my case I am still felling difficult to write unit test for this two functions.
bankaccount.py
class BankAccount():
def __init__(self):
self.account_number=0
self.pin_number=""
self.balance=0.0
self.interest=0.0
self.transaction_list=[]
def deposit_funds(self, amount):
self.balance+=amount
def withdraw_funds(self, amount):
if amount<=balance:
self.balance-=amount
import unittest
from bankaccount import BankAccount
class TestBankAcount(unittest.TestCase):
def setUp(self):
# Create a test BankAccount object
self.account = BankAccount()
# Provide it with some property values
self.account.balance = 1000.0
def test_legal_deposit_works(self):
# code here to test that depsositing money using the account's
# 'deposit_funds' function adds the amount to the balance.
self.assertTrue(100,self.account.deposit_funds(100))
def test_illegal_deposit_raises_exception(self):
# code here to test that depositing an illegal value (like 'bananas'
# or such - something which is NOT a float) results in an exception being
# raised.
unittest.main()
You could do something like this:
Have your class raise an error when the type of values provided to deposit_funds
does not match the use case.
class BankAccount:
def __init__(self):
self.account_number = 0
self.pin_number = ""
self.balance = 0.0
self.interest = 0.0
self.transaction_list = []
def deposit_funds(self, amount):
try:
self.balance += amount
except TypeError:
raise TypeError
def withdraw_funds(self, amount):
if amount <= balance:
self.balance -= amount
Have your tests detect that a TypeError
is thrown when that happens.
class TestBankAcount(unittest.TestCase):
def setUp(self):
self.test_account = BankAccount()
self.test_account.balance = 1000.0
def test_legal_deposit(self):
expected_balance = 1100.0
self.test_account.deposit_funds(100.0)
self.assertEqual(expected_balance, self.test_account.balance)
def test_illegal_deposit_raises_exception(self):
# code here to test that depositing an illegal value (like 'bananas'
# or such - something which is NOT a float) results in an exception being
# raised.
with self.assertRaises(TypeError):
self.test_account.deposit_funds('dummy value')
if __name__ == '__main__':
unittest.main()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.