Programming / Rust

Rust assertions

Out of the box, Rust only comes with couple of assert options:

assert! assert_eq! assert_ne!
Code language: Rust (rust)

First thing – Rust macros have the exclamation mark at the end, and the assertions macro are no different. Unlike the regular annoyance of the exclamation mark, when it’s at the end of an assertion, it’s confusing. If you only program in Rust, maybe you’ll get use to it; but if you’re using other languages as well – it’s an eye sore. Every time that I use these macro I think to myself – they should have come with something better.

Second thing, things are missing. There is no false assertion, greater than and so on. Yes, you can use the standard ones with ==false and alike, but there is a reason why most assertions have these features: it makes things clearer. The point of tests is not just to prove that a code is working, but to provide an actual an readable documentation. When the tests are less descriptive, it affects the readability of the code.

More asserts

Interesting crate is the more_asserts crate that includes additional macros like greater and little than (but still, no false macro).

Trying the more asserts crate:

First, if you want to update your rust version:

rustup update

Lets create a new package:

cargo new hello_world --bin

We now should add the dependency to the toml file to include this mini-library:


And then you can add these lines to the file

#[test] fn assert1() { assert_le!(3, 4); }
Code language: Rust (rust)

Another interesting project is the galvanic-assert, that tries to give a mocha-like flavor to the rust assertions (mocha is one of the best assertion options for node JS, if you like Nodejs, you’re probably familiar with it). Why isn’t that feature already included? Who knows. But don’t skimp on your assertions! I love things right out of the box as much as the other guy, however, this is something worth adding to your toml file:


The code, however is a little bit weird, as in some cases a reference must be taken, so a straight forward code like

fn test_galvanic1() { assert_eq!(3,2+1); }
Code language: Rust (rust)

Has to be written like this:

fn test_galvanic1() { assert_that!(&(1+2),eq(3)); // this is also correct! assert_that!(&(1+2), is(eq(3))); }
Code language: Rust (rust)

This library also includes the has_structure!, is_variant! macros and helpers constructs to make them more wordy.

Why isn’t that part of the standard? Best guess is the time frame and the fact that rust is still new. I believe that with time, much needed packages will be added and will be part of the language.

Leave a Reply

Your email address will not be published. Required fields are marked *