def test_method_called_twice(self): # With the same setup as above, calling the same method a second time will raise an error. 2 `Expect` # statements are required for that. with Expectations(): Expect("SomeAPI").to_receive("get_something").with_args("foo", "bar").and_return(False) SomeAPI.get_something("foo", "bar") assert_raises(ExpectationError, SomeAPI.get_something, "foo", "bar")
def test_method_return(self): # Expecting the function `get_something` to be called, with specifc arguments passed to it, and overriding its # behavior to return a desired output. This test case checks that the method is called, with the right input, # and modifies its return value(s). Can be useful in case the `get_something` performs a call to an external # service that you want to avoid in test environment, and therefore want to mock the response with your output. Expect("SomeAPI").to_receive("get_something").with_args("foo", "bar").and_return(False) # This example is silly of course. Instead, some more complex logic in your module would trigger the call # to `get_something` with the specific input you expect. Here, we mock the output with a `return False`. assert not SomeAPI.get_something("foo", "bar")
def test_instance_method(self): # Everything works with instance methods with Expectations(): Expect("SomeAPI").to_receive("update_attribute").and_return("sshhhh") assert SomeAPI().update_attribute("secret_value") == "sshhhh"
def test_static_method(self): # Everything works with staticmethods defined with Expectations(): Expect("SomeAPI").to_receive("compute_sum").with_args(1, 2).and_return(4) assert SomeAPI.compute_sum(1, 2) == 4
def test_method_return_only(self): # Similar example as above, with no check of arguments passed to `get_something`. with Expectations(): Expect("SomeAPI").to_receive("get_something").and_return(42) assert SomeAPI.get_something("foo", "bar") == 42