Central interface to stub functions on a given `obj` `obj` should be a module, a class or an instance of a class; it can be a Dummy you created with :func:`mock`. ``when`` exposes a fluent interface where you configure a stub in three steps:: when( ). ( ).t
(obj, strict=None)
| 149 | |
| 150 | |
| 151 | def when(obj, strict=None): |
| 152 | """Central interface to stub functions on a given `obj` |
| 153 | |
| 154 | `obj` should be a module, a class or an instance of a class; it can be |
| 155 | a Dummy you created with :func:`mock`. ``when`` exposes a fluent interface |
| 156 | where you configure a stub in three steps:: |
| 157 | |
| 158 | when(<obj>).<method_name>(<args>).thenReturn(<value>) |
| 159 | |
| 160 | Compared to simple *patching*, stubbing in mockito requires you to specify |
| 161 | conrete `args` for which the stub will answer with a concrete `<value>`. |
| 162 | All invocations that do not match this specific call signature will be |
| 163 | rejected. They usually throw at call time. |
| 164 | |
| 165 | Stubbing in mockito's sense thus means not only to get rid of unwanted |
| 166 | side effects, but effectively to turn function calls into constants. |
| 167 | |
| 168 | E.g.:: |
| 169 | |
| 170 | # Given ``dog`` is an instance of a ``Dog`` |
| 171 | when(dog).bark('Grrr').thenReturn('Wuff') |
| 172 | when(dog).bark('Miau').thenRaise(TypeError()) |
| 173 | |
| 174 | # With this configuration set up: |
| 175 | assert dog.bark('Grrr') == 'Wuff' |
| 176 | dog.bark('Miau') # will throw TypeError |
| 177 | dog.bark('Wuff') # will throw unwanted interaction |
| 178 | |
| 179 | Stubbing can effectively be used as monkeypatching; usage shown with |
| 180 | the `with` context managing:: |
| 181 | |
| 182 | with when(os.path).exists('/foo').thenReturn(True): |
| 183 | ... |
| 184 | |
| 185 | Most of the time verifying your interactions is not necessary, because |
| 186 | your code under tests implicitly verifies the return value by evaluating |
| 187 | it. See :func:`verify` if you need to, see also :func:`expect` to setup |
| 188 | expected call counts up front. |
| 189 | |
| 190 | If your function is pure side effect and does not return something, you |
| 191 | can omit the specific answer. The default then is `None`:: |
| 192 | |
| 193 | when(manager).do_work() |
| 194 | |
| 195 | `when` verifies the method name, the expected argument signature, and the |
| 196 | actual, factual arguments your code under test uses against the original |
| 197 | object and its function so its easier to spot changing interfaces. |
| 198 | |
| 199 | Sometimes it's tedious to spell out all arguments:: |
| 200 | |
| 201 | from mockito import ANY, ARGS, KWARGS |
| 202 | when(requests).get('http://example.com/', **KWARGS).thenReturn(...) |
| 203 | when(os.path).exists(ANY) |
| 204 | when(os.path).exists(ANY(str)) |
| 205 | |
| 206 | .. note:: You must :func:`unstub` after stubbing, or use `with` |
| 207 | statement. |
| 208 |