3

I have a function in python that creates an isntance of a Projectclass. If there is no data available, a default instance is created. The code in python is similar to this:

def create_project(data):
  try:
    if data:
      return module.Project(data)
    else:
      return DefaultProject() 
  except:
    raise Exception("Can't create project.')

I want to test, if the constructor of the Project class is called with the right parameter. I already test, if the constructor is called with the following test:

@mock.patch('module')
def test_create_to_return_created_project(self, module_mock):
    #arrange
    project = mock.MagicMock()
    module_mock.Project = mock.MagicMock(return_value = project)

    #act
    result = module.create_project('some_data')

    #assert
    self.assertEqual(result, project)

Now I want to test, if the constructor of the Project class gets the right parameter value with the following code:

@mock.patch('module')
def test_create_project_with_right_parameter(self, module_mock):
  #arrange
  mockProject = mock.MagicMock()
  module_mock.Project = mockProject

  #act
  module.create_project('some_data')

  #assert
  mockProject.__init__.assert_called('some_data')

But the code results in the error:

Message: 'function' object has no attribute 'assert_called'

Does anybody know how to test, if the constructor of the Project class is called with the right parameter?

scher
  • 1,813
  • 2
  • 18
  • 39
  • The error message thrown is pretty obvious, so what's the question here? – Jeronimo Jan 23 '18 at 12:26
  • @Jeronimo I want to know, how to test, that the constructor is called with the right parameter value. Sorry for beeing unclear. – scher Jan 23 '18 at 12:55
  • Depends. Is this your own class? Then you could always save the parameters to some variable inside the constructor and check those later. If not, I'd check how the arguments influence the instance, so that I could find out indirectly what it was. Another idea would be to create a subclass and implement the argument saving there. But AFAIK there is no implicit way of listing the exact arguments afterwards. – Jeronimo Jan 23 '18 at 13:26
  • sadly its not my own class. so just subclassing would do it. Thanks for the inspiration – scher Jan 23 '18 at 14:09
  • refer to the link: https://stackoverflow.com/questions/35711975/asserting-that-init-was-called-with-right-arguments – xavlock Feb 18 '20 at 20:29

1 Answers1

0

The assertion you actually want to check is simply at the mock_project, and not the mock_project __init__.

refer to the link: Asserting that __init__ was called with right arguments

xavlock
  • 31
  • 2
  • 11