Hot questions for Using Mockito in python 3.x
Question:
I'm writing test cases using Mockito. My code looks like this
def function_to_test(): dog = lib1.get_dog() return dog.weight
My test code looks like this
def test_method1(): dog_mock = mock() when(lib1).get_dog().thenReturn(dog_mock) when(dog).weight.thenReturn(10) # <-- I'm not sure how do I write this?
As dog.weight
is not a method. How do I mock it?
Answer:
Not familiar with Mockito framework for Python, but I think you should just set the property on the mock object. Something like that:
dog_mock = mock() dog_mock.weight = 100 when(lib1).get_dog().thenReturn(dog_mock)
Question:
Using mockito in python for a scenario like this:
import os import unittest from mockito import when, verify def interesting_function(): os.system('mkdir some_dir') another_function() def another_function(): print('Done')
Something like this works:
class InterestingFunctionTests(unittest.TestCase): def test_interesting_function(self): when(os).system('mkdir some_dir').thenReturn(0) interesting_function() verify(os).system('mkdir some_dir')
But how can I mock another_function
? Is this even possible? Can I mock methods which exist outside of classes? Something like this for example does not work:
class InterestingFunctionTests(unittest.TestCase): def test_interesting_function(self): when(file_name).another_function().thenReturn() interesting_function() verify(file_name).another_function()
Answer:
You can use when2 with function. There is no verify2
working similarily with functions though.
class InterestingFunctionTests(unittest.TestCase): def test_interesting_function(self): with when2(another_function, ANY).thenReturn(): interesting_function() # verify() ??
Update:
Functions are also objects in Python, so what you can do is:
class InterestingFunctionTests(unittest.TestCase): def test_interesting_function(self): when(another_function).__call__().thenReturn() interesting_function() verify(another_function).__call__()