0

I found I often use same pattern in tests again and again:

mock_get_data = mock.MagicMock()
mock_get_data.get_data.return_value = "mocked DB data"
mock_db = mock.Mock(spec=DBClass, return_value=mock_get_data)

It would be used for testing (with patching) that type of code:

db_connector = DBClass(settings)
print db_connector.get_data()

Is any way to make that 'double mock' thing shorter?

George Shuklin
  • 6,952
  • 10
  • 39
  • 80

2 Answers2

0

You can do like this:

mock_db = mock.Mock(spec=DBClass, return_value=mock.Mock(get_data=lambda:"mocked DB data"))
Oleksandr Dashkov
  • 2,249
  • 1
  • 15
  • 29
0

You should be able to do this by passing in a dictionary to the constructor, as described in the configure mock section of the docs, instead of configuring it after the MagicMock is created.

I believe the following would achieve the desired result:

mock_db = mock.Mock(spec=DBClass, return_value=mock.MagicMock(**{"get_data.return_value": "mocked DB data"})
sytech
  • 29,298
  • 3
  • 45
  • 86