Вопрос

I am integrating mockito with python unittest. I am new to unittest but certainly not new to unit testing paradigm. I wanted to use mockito for stubbing and mocking the classes. I could not find any good documentation on mockito python-unittest integrations and usage.

Is mockito best way forward to it?

what are its implications?

Can any one guide me in this?

Это было полезно?

Решение

I found the documentation for mock easier to understand than for mockito. And it is part of the standard library now.

The python mockito lilbrary is trying to remodel the Java mockito library. So it is useful for people who work with Java and with Python at the same time tp make it easier. If you do not work with Java mockito or not anymore I see no reason to go that path.

Probably your answer ist to use mock, because you are asking "Is mockito best way forward to it?"

From the documentation: http://www.voidspace.org.uk/python/mock/getting-started.html#using-mock


The simple ProductionClass below has a closer method. If it is called with an object then it calls close on it.

>>> class ProductionClass(object):
...     def closer(self, something):
...         something.close()
...

So to test it we need to pass in an object with a close method and check that it was called correctly.

>>> real = ProductionClass()
>>> mock = Mock()
>>> real.closer(mock)
>>> mock.close.assert_called_with()

Often you want to track more than a single call to a method. The mock_calls attribute records all calls to child attributes of the mock - and also to their children.

>>> mock = MagicMock()
>>> mock.method()
<MagicMock name='mock.method()' id='...'>
>>> mock.attribute.method(10, x=53)
<MagicMock name='mock.attribute.method()' id='...'>
>>> mock.mock_calls
[call.method(), call.attribute.method(10, x=53)]

If you make an assertion about mock_calls and any unexpected methods have been called, then the assertion will fail. This is useful because as well as asserting that the calls you expected have been made, you are also checking that they were made in the right order and with no additional calls:

You use the call object to construct lists for comparing with mock_calls:

>>> expected = [call.method(), call.attribute.method(10, x=53)]
>>> mock.mock_calls == expected
True

Setting the return values on a mock object is trivially easy:

>>> mock = Mock()
>>> mock.return_value = 3
>>> mock()
3

Of course you can do the same for methods on the mock:

>>> mock = Mock()
>>> mock.method.return_value = 3
>>> mock.method()
3

The return value can also be set in the constructor:

>>> mock = Mock(return_value=3)
>>> mock()
3

If you need an attribute setting on your mock, just do it:

>>> mock = Mock()
>>> mock.x = 3
>>> mock.x
3
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top