Run `assert` on Drop
jyn514 opened this issue · comments
Right now, any user of the API has to remember to call Mock::assert
at the end of each and every test. If they forget, the mock doesn't actually test anything. It would be nice for this to be called automatically without the user having to remember.
Originally reported by @jyn514 in deadlinks/cargo-deadlinks#94 (comment)
That's an interesting idea, but I wonder if there are use-cases where this could become a problem. Generally I prefer to be explicit here and I've seen other testing frameworks doing the same. I'll give it a thought before the 1.0. In any case, it would be a breaking change.
I wonder if there are use-cases where this could become a problem
You could always mem::forget
the Mock if you didn't actually want to run the assert.
I don't feel super strongly about this, but I do think it would be a nice QOL improvement.
Instead of making it a breaking change it could also be an opt-in option, maybe when creating the server url. I've just run into cases where I forgot to assert and the tests stayed green - such option would've helped.
Also when a test has a couple of mocks the explicit assertion gets tedious - though I generally agree, explicit > implicit.
I was also a bit confused by this.
Perhaps there is still value in explicitly calling assert
but definitely calling it on Drop seems definitely desirable; it's a mock object after all. If its purpose is not to be asserted at some point then what is really the purpose?
+1
I was surprised as well that I need to call it explicitly instead of something more like a gmock-style. Cases where someone didn't want an assertion, but it fired by its own will be caught right away, in contrary to forgetting about it when it was desired.
@jyn514 @johannescpk @horacimacias @podusowski took a while but this was addressed in #191 and is now availabe in 1.3.0 as an optional server config:
{
let opts = mockito::ServerOpts { assert_on_drop: true, ..Default::default() };
let mut server = mockito::Server::new_with_opts(opts);
// let mut async_server = mockito::Server::new_with_opts_async(opts).await;
let _mock = s.mock("GET", "/hello").create();
}
// This will panic automatically since the mock was never requested before going out of scope
Note that using Server::new_with_opts
bypasses the server pool, though that shouldn't be a problem for most use cases.