Building tests for our Rust package
Previously, in Chapter 4, Building pip Modules in Python, we built unit tests for our Python code. In this section, we will build unit tests for our Fibonacci functions. These tests do not need any extra packages or dependencies. We can use Cargo to manage our testing. This can be done by adding our testing code in the src/fib_calcs/fib_number.rs
file. The steps are as follows:
- We do this by creating a module in the
src/fib_calcs/fib_number.rs
file with the following code:#[cfg(test)] mod fibonacci_number_tests { use super::fibonacci_number; }
Here, we can see that we have defined a module in the same file and decorated the module with the
#[cfg(test)]
macro. - We can also see that we must import the function, as it is super to the module. Inside this module, we can run standard tests that check to see whether the integers we pass in calculate the Fibonacci number we expect with the following code:
...