Sharing common code

As is often the case with integration tests, there is some setup and teardown-related code that we might need to put in place before we can actually run our tests. You usually want them to be shared by all of the files in the tests/ directory. For sharing code, we can use modules by either creating them as a directory that shares common code, or use a module foo.rs and declare in our integration test files that we depend on it by putting a mod declaration. So, in our preceding tests/ directory, we added a common.rs module that has two functions called setup and teardown:

// integration_test/tests/common.rs

pub fn setup() {
println!("Setting up fixtures");
}

pub fn teardown() {
println!("Tearing down");
}

In both of our functions, we can have any kind of fixture-related code. Consider that you have an integration test that relies on the existence of a text file. In our function setup, we can create the text file, while in our functi0n teardown, we can clean up our resources by deleting the file.

To use these functions in our integration test code in tests/sum.rs, we put in the mod declarations like so:

// integration_test/tests/sum.rs

use integration_test::sum;

mod common;

use common::{setup, teardown};

#[test]
fn sum_test() {
assert_eq!(sum(6, 8), 14);
}

#[test]
fn test_with_fixture() {
setup();
assert_eq!(sum(7, 14), 21);
teardown();
}

We have added another function,  test_with_fixture , that includes calls to setup and teardown. We can run this test with cargo test test_with_fixture. As you may have noticed from the output, we don't get to see our println! calls anywhere from within the setup or teardown functions. This is because, by default, the test harness hides or captures print statements within test functions to make the test results tidier, and only shows the test harness's outputs. If we want to view print statements within our tests, we can run the test with cargo test test_with_fixture -- --nocapture, which gives us the following output:

We can see our print statements now. We needed the -- in cargo test test_with_fixture -- --nocapture because we actually want to pass the --nocapture flag to our test runner. -- marks the end of arguments for cargo itself, and any argument following that is passed to the binary being invoked by cargo, which is our compiled binary with test harness.

That's about it for integration tests. At the end of this chapter, we'll create a project where we get to see both unit tests and integration tests work in tandem. Next, we'll learn about documenting Rust code, an overlooked but quite important part of software development.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset