I have following piece of code to UT, which makes me in trouble:
def initialize():
try :
self.client = MongoClient("127.0.0.1", 27017)
self.conn = self.client["DB_NAME"]
except Exception:
print "Except in initialize!"
return False
return True
I write following test case to cover the above function, hope to get return value "True":
def mock_mongodb_mongoclient_init(self, para1, para2):
pass
def mock_mongodb_mongoclient_getitem(self, name):
return {"DB_NAME":"Something"}
def test_mongodb_initialize_true(self):
self.patcher1 = patch('pymongo.MongoClient.__init__', new=self.mock_mongodb_mongoclient_init)
self.patcher2 = patch('pymongo.MongoClient.__getitem__', new=self.mock_mongodb_mongoclient_getitem)
self.patcher1.start()
self.patcher2.start()
self.assertEqual(initialize(), True)
self.patcher1.stop()
self.patcher2.stop()
But this never works! It always report "Exception in initialize!"! and return "False".
How could I UT this MongoClient and makes the function return "True"?
Since you are unit testing and not trying to actually connect to Mongo in any way, I think you should just care that the client API has been called. So I would suggest the following -
from unittest import mock
@mock.patch("pymongo.MongoClient")
def test_mongodb_initialize(self, mock_pymongo):
MyMongo.initialize()
self.assertTrue(mock_pymongo.called)
(Forgive me if my syntax is off, I use pytest rather than unittest.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With