I am trying to check how many times I call the acc.add
method in the Car.run
method using Python unittest, but I can't figure out how to do it. This is what I tried:
Car and Accessories:
class Accessories(AccessoriesAbstract):
def __init__(self):
self.sum = 0
super().__init__()
def add(self, index, name):
self.sum += index
return self.sum
class Car(CarAbstract):
def __init__(self, acc: Accessories):
self.acc = acc
super().__init__(acc)
def run(self):
self.acc.add(2, "bob")
result = self.acc.add(5, "rob")
if result > int(sys.maxsize) - 10:
raise ValueError
And test:
@patch('car_code.Car')
def test_car_run(self, MockCar):
car = MockCar()
response = car.run()
self.assertIsNotNone(response)
car.run.acc.add.assert_called()
You need to mock an instance of the Accessories
class instead and then pass that instance to the Car
constructor. For example:
# Create an Accessories object
acc = Accessories()
# Create a mock object that "wraps" the Accessories object
mock_acc = Mock(wraps=acc)
# Pass the mock object when you create the Car object
car = Car(mock_acc)
car.run()
# Then you'll be able to get the call_count like this:
mock_acc.add.call_count
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.