官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 平南县| 镇安县| 石家庄市| 江安县| 洛隆县| 漳平市| 肇东市| 铜山县| 丹凤县| 新丰县| 富阳市| 和硕县| 鹤峰县| 新晃| 高要市| 枣庄市| 金塔县| 沈丘县| 新乐市| 章丘市| 湟源县| 南汇区| 彭州市| 五大连池市| 桂林市| 龙胜| 松原市| 裕民县| 洪洞县| 山东省| 沾化县| 习水县| 玉龙| 阿尔山市| 明溪县| 台州市| 石门县| 绵阳市| 那坡县| 会同县| 宝丰县|