python - How to access object instance from mocked instance method when unit testing? -
in code below says foo_obj = ????
, how can reference foo object instance, or better approach?
class foo(object): def __init__(self): self.hello = "hey!" def bar(self): return self.hello + " how's going?" def side_effect_foo_bar(*args, **kwargs): foo_obj = ???? return foo_obj.hello + " what's up?" class testfoo(unittest.testcase): @patch.object(foo, 'bar') def test_bar(self, mocked_bar): mocked_bar.side_effect = side_effect_foo_bar foo = foo() self.asserttrue(foo.bar() == "hey! what's up?")
i figured out this:
http://mock.readthedocs.org/en/latest/examples.html#mocking-unbound-methods
the trick add autospec=true
in @patch.object(foo, 'bar', autospec=true)
.
class foo(object): def __init__(self): self.hello = "hey!" def bar(self): return self.hello + " how's going?" def side_effect_foo_bar(*args, **kwargs): return args[0].hello + " what's up?" class testfoo(unittest.testcase): @patch.object(foo, 'bar', autospec=true) def test_bar(self, mocked_bar): mocked_bar.side_effect = side_effect_foo_bar foo = foo() self.asserttrue(foo.bar() == "hey! what's up?")
Comments
Post a Comment