Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I mock a superclass's __init__ create an attribute containing a mock object for a unit test?
    primarykey
    data
    text
    <p>I am attempting to write a unit test for a class's <code>__init__</code>:</p> <pre><code>def __init__(self, buildNum, configFile = "configfile.txt"): super(DevBuild, self).__init__(buildNum, configFile) if configFile == "configfile.txt": self.config.MakeDevBuild() </code></pre> <p>The config attribute is set by the super's <code>__init__</code>. I'm using <a href="http://mock.readthedocs.org/en/latest/index.html">mock</a>, and I want the config attribute to be a mock object. However, I haven't been able to figure out how to actually make that happen. Here's the best I could come up with for the test:</p> <pre><code>def test_init(self): with patch('DevBuild.super', create=True) as mock_super: mock_MakeDevBuild = MagicMock() mock_super.return_value.config.MakeDevBuild = mock_MakeDevBuild # Test with manual configuration self.testBuild = DevBuild("42", "devconfigfile.txt") self.assertFalse(mock_MakeDevBuild.called) # Test with automated configuration self.testBuild = DevBuild("42") mock_MakeDevBuild.assert_called_once_with() </code></pre> <p>However, this doesn't work--I get an error:</p> <pre><code>Error Traceback (most recent call last): File "/Users/khagler/Projects/BuildClass/BuildClass/test_devBuild.py", line 17, in test_init self.testBuild = DevBuild("42") File "/Users/khagler/Projects/BuildClass/BuildClass/DevBuild.py", line 39, in __init__ self.config.MakeDevBuild() AttributeError: 'DevBuild' object has no attribute 'config' </code></pre> <p>Clearly I'm not setting the config attribute correctly, but I have no idea <em>where</em> exactly I should be setting it. Or for that matter, if what I want to do is even possible. Can anyone tell me what I need to do to make this work?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload