This module is a port of the
Mockito mocking framework to Python. Install mockito with
easy_install:
easy_install mockito
Suppose you need to test withdraw operation in ATM (file
atm.py):
from datetime import datetime
class Atm:
def signin(self, account):
self._account = account
def signout(self):
self._account = None
def withdraw(self, amount):
try:
self._account.withdraw(amount)
self._account.comission(amount * 0.005)
except ValueError:
self._account.comission(amount * 0.001)
return self._account.balance(datetime.now())
Here is our test (file
mockitoexample.py):
from datetime import datetime
from atm import Atm
import unittest
from mockito import Mock, when, verify, any, verifyNoMoreInteractions
class TestAtm(unittest.TestCase):
def setUp(self):
self._mock_account = Mock()
self._atm = Atm()
self._atm.signin(self._mock_account)
def tearDown(self):
self._atm.signout()
verifyNoMoreInteractions(self._mock_account)
def test_withdraw(self):
# Arrange
when(self._mock_account).balance(any(datetime))\
.thenReturn(49.5)
# Act
self._mock_account.deposit(150)
remaining_balance = self._atm.withdraw(100)
# Assert
assert remaining_balance == 49.5
verify(self._mock_account).deposit(150)
verify(self._mock_account).withdraw(100)
verify(self._mock_account).comission(0.5)
verify(self._mock_account).balance(any(datetime))
def test_withdraw_insufficient_funds(self):
# Arrange
when(self._mock_account).withdraw(100)\
.thenRaise(ValueError('Insufficient funds'))
when(self._mock_account).balance(any(datetime))\
.thenReturn(49.9)
# Act
self._mock_account.deposit(50)
remaining_balance = self._atm.withdraw(100)
# Assert
assert remaining_balance == 49.9
verify(self._mock_account).deposit(50)
verify(self._mock_account).withdraw(100)
verify(self._mock_account).comission(0.1)
verify(self._mock_account).balance(any(datetime))
if __name__ == '__main__':
unittest.main()
Run tests:
python mockitoexample.py
Read more about mockito
here.
No comments :
Post a Comment