Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #95358
| From | Ben Finney <ben+python@benfinney.id.au> |
|---|---|
| Subject | Re: Mock object but also assert method calls? |
| Date | 2015-08-14 07:21 +1000 |
| References | <509adc48-996d-44b0-abf1-e15ee387023b@googlegroups.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.178.1439500927.3627.python-list@python.org> (permalink) |
Thomas Lehmann via Python-list <python-list@python.org> writes:
> How about asserting that test2 of class Bar is called?
It is unusual to call class methods; do you mean a method on an
instance?
You will make a mock instance of the class, or a mock of the class; and
you'll need to know which it is.
> Of course I can do a patch for a concrete method but I was looking for
> something like:
>
> mocked_object.assert_method_called_with(name="test2", "hello")
The ‘mock’ library defaults to providing ‘MagicMock’, which is “magic”
in the sense that it automatically provides any attribute you request,
and those attributes are themselves also MagicMocks::
import unittest.mock
def test_spam_calls_foo_bar():
""" Should call the `spam` method on the specified `Foo` instance. """
mock_foo = unittest.mock.MagicMock(system_under_test.Foo)
system_under_test.spam(mock_foo)
mock_foo.spam.assert_called_with("hello")
> If find following totally different to the normal API which
> is provided by the mock library:
>
> assert call().test2("hello") in mocked_objects.mock_calls
The ‘assert’ statement is a crude tool, which knows little about the
intent of your assertion. You should be instead using the specialised
methods from ‘unittest.TestCase’ and the methods on the mock objects
themselves.
--
\ “It is the mark of an educated mind to be able to entertain a |
`\ thought without accepting it.” —Aristotle |
_o__) |
Ben Finney
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Mock object but also assert method calls? Thomas Lehmann <thomas.lehmann.private@googlemail.com> - 2015-08-13 08:58 -0700
Re: Mock object but also assert method calls? Ben Finney <ben+python@benfinney.id.au> - 2015-08-14 07:21 +1000
Re: Mock object but also assert method calls? Steven D'Aprano <steve@pearwood.info> - 2015-08-14 12:53 +1000
Re: Mock object but also assert method calls? Thomas Lehmann <thomas.lehmann.private@googlemail.com> - 2015-08-15 04:07 -0700
csiph-web