How to mock patch every method of a class

Viewed 2232

I have a Test class with as many as 50 different method. I want to patch every method with a mock function.

prod = {"foo": "bar"}

def TestClass:
  @patch(db.get_product, return_value=prod)
  def test_1:
    pass
  @patch(db.get_product, return_value=prod)
  def test_2:
    pass
  .
  .
  .
  @patch(db.get_product, return_value=prod)
  def test_50:
    pass

Is there any easy way to do this instead of repeating @patch(db.get_product, return=prod) 50 times?

1 Answers

You can use patch as a class decorator instead:

@patch(db.get_product, return_value=prod)
class TestClass:
  def test_1:
    pass
  def test_2:
    pass
  .
  .
  .
  def test_50:
    pass

Excerpt from the documentation:

Patch can be used as a TestCase class decorator. It works by decorating each test method in the class. This reduces the boilerplate code when your test methods share a common patchings set.

Related