In this post I will go over how to write Unit test for your Rust application. We will continue with where we left off with the hello world program and see what Rust has to offer us in unit testing. Note: I will be Writing and Running Intergration Tests with Rust in VSCode.

Creating Rust test directory

Our directory would look something like below.

In our file we will add the code like below, if you are coming from a C# or Java background, Rust also uses Attribute for test so it will look quite familiar, using # tag followed by [test] brackets. We are using assert! just to pass this test.

To run the test we can run the cargo test command like below.

If you remember we had our program output a simple println statement with Hello, world!, so our test needs to check the output of our program. In order to do so we will introduce a new cargo package into your system.

Lets modify our project dependency and use crate assert_cmd to find the program in our crate directory.

Adding development dependency to Cargo.toml

Open the file Cargo.toml and add the dev dependency like below.

Now we will need to modify our file we will add the usage of the assert_cmd package.

Above you will see that I am using assert_cmd and have changed some of the code to use the Command library. In the above code you will also see I am using a strange variable naming “let mut”. You may wonder what that is?

let mut what is that?

So variables in Rust are immutable by default, and require the mut keyword to be made mutable here. I am also using cargo_bin so that it can automatically find the output of the hello world program.

Unwrap what is that?

You also see I am calling a function called unwrap, so unwrap() is used here to handle the errors quickly in our test. It can be used on any function that returns Result or Option (Option is also an enum). If the function returns an Ok(value), you will get the value. If the function returns an Err(error), the program/test will panic. In our case if it does not find the hello program it will be in panic mode.

Next I have used assert with success to find out the command was successful and trying to match the Hello, world! output. If we run this test we will see that it will fail.

One may wonder what is wrong with it, so basically what we are missing is the newline character in our test \n in our stdout, so lets modify our test code and add the newline character.

Now the output of our test should be passing.


I understand the fact that this is a very brittle test checking the output of our program to match a certain string. The idea of this is for you to learn how to write simple unit test in Rust and how the ecosystem works. I hope this helps in your journey, we will continue on our learning Rust journey to write simple unix/linux command line tools and built upon that.