Open In App

Rust – Tests

Last Updated : 28 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Rust, there are specific procedures that are needed to be adhered to before writing the tests. The steps for writing the tests are as follows:

Step 1: Setting up data/states required by our code.

Step 2: Run the code for the tests we need to test.

Step 3: Asserting the expected results.

In Rust, we annotate the functions with the test attributes which are nothing but metadata about the information about Rust. 

To run tests, we use the cargo command. When running the tests, the cargo compiler builds the test runner binary, and then it reports to us whether the annotated function passes or fails. 

Now we take an example, we create a library project called multiply that multiplies two numbers.

cargo new multiply –lib

cd multiply

 

 

Example 1: 

Rust




#[cfg(test)]
mod tests {
    #[test]
    fn multiply_function() {
        let result = 5*5;
        assert_eq!(result, 25);
    }
}


Output:

Now, we run the code using cargo test. After running the tests, we get output:

 

Explanation:

In this example, we use the #test annotation which is an attribute that indicates the test function, hence the test runner in Rust treats this function as a test. We use the assert_eq! macro so that the result of multiplying 5 and 5, equals 25. This assertion helps in running tests. Once, we use the command cargo test, we can see in the output that there is a test running called to multiply the result which is Ok which implies that the tests  have successfully

Example 2:

Rust




#[cfg(test)]
mod tests {
  
    #[test]
    fn test_one() {
        let result = 5 * 5;
        assert_eq!(result, 25);
    }
  #[test]
    fn test_two() {
        panic!("test_two is failed");
    }
}


Output:

On running the cargo test, we get the following output

 

Explanation:

In this example, we have continued from example 01 where we have used the multiply function. Here, we have used two tests named test_one and test_two. We have used the panic! keyword intentionally here so that one of the tests fails while test_one gets passed (i.e. asserted correctly)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads