dashbitco / mox

Mocks and explicit contracts in Elixir
1.35k stars 77 forks source link

Suggestion: Mox.not_expect/3 #121

Closed prodis closed 2 years ago

prodis commented 2 years ago

When expecting that a mock function is not called, the Mox.expect/4 is used passing the n parameter as 0.

My suggestion is to create a DSL function with the same behaviour but not using the n parameter.

Example

Using Mox.expect/4:

expect(MockWeatherAPI, :get_temp, 0, fn _ -> {:ok, 30} end)

With the new Mox.not_expect/3:

not_expect(MockWeatherAPI, :get_temp, fn _ -> {:ok, 30} end)

Furthermore, the third parameter code could be optional:

not_expect(MockWeatherAPI, :get_temp)

Any other suggestions for the function name are welcome.

Thoughts? 🙂

P.S.: In case of acceptance, I would like to implement it. 🙏

zekus commented 2 years ago

refute or reject maybe is a better name ;)

josevalim commented 2 years ago

Could you implement not_expect as calling expect except you raise an error?

ericmj commented 2 years ago

I think it would be equivalent to: Mox.stub(..., fn -> flunk("should not be called") end).

msz commented 2 years ago

When expecting that a mock function is not called, the Mox.expect/4 is used passing the n parameter as 0.

An easier (and perhaps more intuitive) way is just not defining any expectation if there is no expectation for a function to be called!

wojtekmach commented 2 years ago

I found a lot of value from this hint: instead of asserting what something is not (eg assert foo != bar), assert what something is (assert foo == baz, assert is_atom(foo), etc). The main reason being is it is very easy for these "negative" assertions to continue passing for the wrong reason, eg system under the hood completely changed and the assertion is now useless, it will never ever fail. This advice does not really work for function calls andnfor that reason, yeah, I agree with @msz and would not test it that way and this would rather not introduce a new function.

josevalim commented 2 years ago

Thanks everyone for the discussion! I think there are enough alternatives right now to justify not adding this to Mox. :)