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

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.

主站蜘蛛池模板: 新野县| 吉安市| 开化县| 镇雄县| 沁阳市| 连江县| 泗洪县| 铁岭市| 阳曲县| 琼中| 金沙县| 通榆县| 遂昌县| 阳江市| 台安县| 江北区| 利津县| 永年县| 平阴县| 边坝县| 黑河市| 洛宁县| 普安县| 溧水县| 道孚县| 庆云县| 马尔康县| 静安区| 得荣县| 宾阳县| 兴海县| 新巴尔虎左旗| 韶山市| 旌德县| 唐山市| 江城| 石景山区| 肥东县| 铁岭县| 景宁| 弥渡县|