Created
November 27, 2014 16:50
-
-
Save tarasn/484471582657a60d2d84 to your computer and use it in GitHub Desktop.
How to replace a class method with mocked method for unit testing?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #http://stackoverflow.com/questions/13073281/how-to-mock-pythons-datetime-now-in-a-class-method-for-unit-testing?rq=1 | |
| from mock import patch | |
| from mock import Mock | |
| import unittest | |
| class MyCalc(object): | |
| def add(self,x ,y): | |
| return x+y | |
| def mul(self,x ,y): | |
| return x*y | |
| def return_something(self): | |
| return "something" | |
| def mocked_return(): | |
| return "mocked" | |
| class MyCalcTest(unittest.TestCase): | |
| def setUp(self): | |
| self.calc = MyCalc() | |
| def test_mul_4_5(self): | |
| self.assertEqual( self.calc.mul(4,5), 20) | |
| def test_add_3_4(self): | |
| self.assertEqual( self.calc.add(3,4), 7) | |
| def test_mul_3_4(self): | |
| self.assertEqual( self.calc.mul(3,4), 12) | |
| def test_return_something(self): | |
| self.assertEqual( self.calc.return_something(), "something") | |
| @patch('__main__.MyCalc.return_something', Mock(side_effect=mocked_return)) | |
| def test_mocked_return(self): | |
| self.assertEqual( self.calc.return_something(), "mocked") | |
| if __name__ == '__main__': | |
| unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment