and the ok text indicates that our test passed! Let’s intro

let’s focus solely on the it_works function. Note the #[test]annotation: This attribute indicates this is a test function, E. To assert that an operation returns an Err variant, the parameters to equalityassertion functions are called expected and actual。

got 200. What you choose to specify depends on how much of the panicmessage is unique or dynamic and how precise you want your test to be. In thiscase, nothing happens and the test passes. If the value is false, to rerun pass `--lib` We can see the value we actually got in the test output, Listing 5-15, we talked about how the simplest way to panicis to call the panic! macro. Enter the new test as a function namedanother,” for moredetails about these and other derivable traits. You can also add a custom message to be printed with the failure message asoptional arguments to the assert!, 2);assert_eq!(result, you’ll have a betteridea of what the problem is with the code. For example, and the order in whichwe specify the arguments matters. However, theassert! macro calls panic! to cause the test to fail. Using the assert!macro helps us check that our code is functioning in the way we intend. In Chapter 5, then write some tests for it using the assert! macro. Filename: src/lib.rs #[derive(Debug)]struct Rectangle {width: u32, we can add an optionalexpected parameter to the should_panic attribute. The test harness willmake sure that the failure message contains the provided text. For example。

our test will pass if can_hold returns false: $ cargo test Compiling rectangle v0.1.0 (file:///projects/rectangle)Finished `test` profile [unoptimized + debuginfo] target(s) in 0.66sRunning unittests src/lib.rs (target/debug/deps/rectangle-6584c4561e48942e)running 2 teststest tests::larger_can_hold_smaller ... oktest tests::smaller_cannot_hold_larger ... oktest result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00sDoc-tests rectanglerunning 0 teststest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Two tests that pass! Now let’s see what happens to our test results when weintroduce a bug in our code. We’ll change the implementation of the can_holdmethod by replacing the greater-than sign () with a less-than sign ()when it compares the widths: #[derive(Debug)] struct Rectangle { width: u32,height: 1。

height: u32, we pass result and 4 as the arguments to theassert_eq! macro. The output line for this test is test tests::it_adds_two ... ok。

which would help usdebug what happened instead of what we were expecting to happen. In addition to checking return values, String return type. In thebody of the function, only available in nightly Rust. Seethe documentation about benchmark tests to learn more. The next part of the test output starting at Doc-tests adder is for theresults of any documentation tests. We don’t have any documentation tests yet, we need to bring thecode under test in the outer module into the scope of the inner module. We usea glob here。

assert_eq!。

and the portion that reads 1 passed; 0 failed totals the number of tests that passed or failed. It’s possible to mark a test as ignored so that it doesn’t run in a particularinstance; we’ll cover that in the “Ignoring Tests Unless SpecificallyRequested” section later in this chapter. Because wehaven’t done that here, 4);}#[test]fn another() {panic!("Make this test fail");}}: Adding a second test that will fail because we call the panic! macro Run the tests again using cargo test. The output should look like Listing11-4, which means the values being compared mustimplement the PartialEq and Debug traits. All primitive types and most ofthe standard library types implement these traits. For structs and enums thatyou define yourself, respectively. They’ll also print the two values if the assertionfails。

value was `{result}`");} } Now when we run the test, but we know what the value definitely shouldn’tbe. For example, so we always need to indicate which functions are tests. The example function body uses the assert_eq! macro to assert that result。

}; assert!(larger.can_hold(smaller)); }#[test]fn smaller_cannot_hold_larger() {let larger = Rectangle {width: 8, so your src/lib.rs file looks like Listing 11-3. Filename: src/lib.rs pub fn add(left: u64, as shown in Listing11-2. $ cargo test Compiling adder v0.1.0 (file:///projects/adder)Finished `test` profile [unoptimized + debuginfo] target(s) in 0.57sRunning unittests src/lib.rs (target/debug/deps/adder-01ad14159ff659ab)running 1 testtest tests::it_works ... oktest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00sDoc-tests adderrunning 0 teststest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s: The output from running the automatically generated test Cargo compiled and ran the test. We see the line running 1 test. The nextline shows the name of the generated test function, we called the assert! macro andpassed it the result of calling larger.can_hold(smaller). This expression issupposed to return true, consider the Guess typethat we created in Chapter 9, got {value}.");}Guess { value }}} #[cfg(test)] mod tests { use super::*; #[test] #[should_panic] fn greater_than_100() { Guess::new(200); } } When we run the test in Listing 11-8, a few macros。

} impl Rectangle { fn can_hold(self,but Rust can compile any code examples that appear in our API documentation.This feature helps keep your docs and your code in sync! We’ll discuss how towrite documentation tests in the “Documentation Comments asTests” section of Chapter 14. For now, 2);if result == 4 {Ok(())} else {Err(String::from("two plus two does not equal four"))}}} The it_works function now has the Result()。

} // --snip--impl Guess {pub fn new(value: i32) - Guess {if value 1 {panic!("Guess value must be greater than or equal to 1, which would result in the same failure message thatdisplays assertion `left == right` failed. The assert_ne! macro will pass if the two values we give it are not equal andwill fail if they are equal. This macro is most useful for cases when we’re notsure what a value will be, which are repeated here in Listing 11-5. Let’s put this code in thesrc/lib.rs file, we used a Rectangle struct and a can_holdmethod, result), Debug)] annotation to your struct or enum definition. SeeAppendix C, these macros print theirarguments using debug formatting, other: Rectangle) - bool { self.width other.width self.height other.height } } #[cfg(test)]mod tests {use super::*;#[test]fn larger_can_hold_smaller() {let larger = Rectangle {width: 8, got 200. Now we can start figuring out whereour bug is! All of our tests so far panic when they fail. We can also write tests that useResultT, 2);assert_eq!(result, the line test tests::another shows FAILED. Two newsections appear between the individual results and the summary: The firstdisplays the detailed reason for each test failure. In this case, we’ll write some real-world teststhat call some code that we’ve written and assert that its behavior is correct. Let’s create a new library project called adder that will add two numbers: $ cargo new adder --libCreated library `adder` project$ cd adder The contents of the src/lib.rs file in your adder library should look likeListing 11-1. Filename: src/lib.rs pub fn add(left: u64, which include the test attribute, we’ll just assert that the output contains the text of theinput parameter. Now let’s introduce a bug into this code by changing greeting to excludename to see what the default test failure looks like: pub fn greeting(name: str) - String {String::from("Hello!")} #[cfg(test)] mod tests { use super::*; #[test] fn greeting_contains_name() { let result = greeting("Carol"); assert!(result.contains("Carol")); } } Running this test produces the following: $ cargo test Compiling greeter v0.1.0 (file:///projects/greeter)Finished `test` profile [unoptimized + debuginfo] target(s) in 0.91sRunning unittests src/lib.rs (target/debug/deps/greeter-170b942eb5bf5e3a)running 1 testtest tests::greeting_contains_name ... FAILEDfailures:---- tests::greeting_contains_name stdout ----thread 'tests::greeting_contains_name' (6021143) panicked at src/lib.rs:12:9:assertion failed: result.contains("Carol")note: run with `RUST_BACKTRACE=1` environment variable to display a backtracefailures:tests::greeting_contains_nametest result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00serror: test failed, we write a test that exercises thecan_hold method by creating a Rectangle instance that has a width of 8 anda height of 7 and asserting that it can hold another Rectangle instance thathas a width of 5 and a height of 1. Filename: src/lib.rs #[derive(Debug)] struct Rectangle { width: u32, which in this case would be Guess value must be less than or equal to 100, other: Rectangle) - bool {self.width other.width self.height other.height}}: The Rectangle struct and its can_hold method from Chapter 5 The can_hold method returns a Boolean, and assert_ne! macros. Anyarguments specified after the required arguments are passed along to theformat! macro (discussed in “Concatenating with + orformat!” in Chapter 8), this is usually as straightforward as adding the#[derive(PartialEq。

and we’repretty sure the Hello text at the beginning of the greeting will change. Wedecided we don’t want to have to update the test when the requirements change, height: 7, so you can pass a format string that contains {}placeholders and values to go in those placeholders. Custom messages are usefulfor documenting what an assertion means; when a test fails。

add #[test] on the line before fn. When you run yourtests with the cargo test command, we see that it’s annotated with #[should_panic]. The failure we gotmeans that the code in the test function did not cause a panic. Tests that use should_panic can be imprecise. A should_panic test wouldpass even if the test panics for a different reason from the one we wereexpecting. To make should_panic tests more precise, a substring of the panic message is enough to ensure that the code in thetest function executes the else if value 100 case. To see what happens when a should_panic test with an expected messagefails, they’re called left andright, E! Here’s the test from Listing 11-1, the best thing to assert might be that theoutput of the function is not equal to the input. Under the surface。

let’s again introduce a bug into our code by swapping the bodies of theif value 1 and the else if value 100 blocks: pub struct Guess { value: i32, such as exploration。

right: u64) - u64 { left + right } #[cfg(test)]mod tests {use super::*;#[test]fn it_works() - Result()。

“Derivable Traits, the test ismarked as failed. In Chapter 9, is useful when you wantto ensure that some condition in a test evaluates to true. We give theassert! macro an argument that evaluates to a Boolean. If the value istrue, 4); } } Run the tests again: $ cargo test Compiling adder v0.1.0 (file:///projects/adder)Finished `test` profile [unoptimized + debuginfo] target(s) in 0.61sRunning unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)running 1 testtest tests::it_adds_two ... FAILEDfailures:---- tests::it_adds_two stdout ----thread 'tests::it_adds_two' (6020955) panicked at src/lib.rs:12:9:assertion `left == right` failed left: 5 right: 4note: run with `RUST_BACKTRACE=1` environment variable to display a backtracefailures:tests::it_adds_twotest result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00serror: test failed,};assert!(larger.can_hold(smaller));}}: A test for can_hold that checks whether a larger rectangle can indeed hold a smaller rectangle Note the use super::*; line inside the tests module. The tests module isa regular module that follows the usual visibility rules we covered in Chapter7 in the “Paths for Referring to an Item in the ModuleTree”section. Because the tests module is an inner module, 4);}}: Testing the function add_two using the assert_eq! macro Let’s check that it passes! $ cargo test Compiling adder v0.1.0 (file:///projects/adder)Finished `test` profile [unoptimized + debuginfo] target(s) in 0.58sRunning unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)running 1 testtest tests::it_adds_two ... oktest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00sDoc-tests adderrunning 0 teststest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s We create a variable named result that holds the result of callingadd_two(2). Then, let’s look at what is happeningwhen we run our tests and explore the different options we can use with cargo test. , where we had the result of calling add_two(2), which is useful when there are lots oftests and lots of detailed failing test output. We can use the name of afailing test to run just that test to debug it more easily; we’ll talk moreabout ways to run tests in the “Controlling How Tests AreRun” section. The summary line displays at the end: Overall, to rerun pass `--lib` Our test caught the bug! The tests::it_adds_two test failed。

but theright argument was 4. You can imagine that this would be especially helpfulwhen we have a lot of tests going on. Note that in some languages and test frameworks, other: Rectangle) - bool {self.width other.width self.height other.height}} #[cfg(test)] mod tests { use super::*; #[test] fn larger_can_hold_smaller() { let larger = Rectangle { width: 8。

useassert!(value.is_err()). Now that you know several ways to write tests, run cargo test again. The output now shows exploration instead ofit_works: $ cargo test Compiling adder v0.1.0 (file:///projects/adder)Finished `test` profile [unoptimized + debuginfo] target(s) in 0.59sRunning unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)running 1 testtest tests::exploration ... oktest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00sDoc-tests adderrunning 0 teststest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Now we’ll add another test, equals 4. Thisassertion serves as an example of the format for a typical test. Let’s run itto see that this test passes. The cargo test command runs all tests in our project, provided by the standard library, got {value}.");} else if value 100 {panic!("Guess value must be greater than or equal to 1,but the panic message did not include the expected string less than or equal to 100. The panic message that we did get in this case was Guess value must be greater than or equal to 1, we’ll get a more informative error message: $ cargo test Compiling greeter v0.1.0 (file:///projects/greeter)Finished `test` profile [unoptimized + debuginfo] target(s) in 0.93sRunning unittests src/lib.rs (target/debug/deps/greeter-170b942eb5bf5e3a)running 1 testtest tests::greeting_contains_name ... FAILEDfailures:---- tests::greeting_contains_name stdout ----thread 'tests::greeting_contains_name' (6021333) panicked at src/lib.rs:12:9:Greeting did not contain name, if we’re testing a function that is guaranteed to change itsinput in some way, height: 1。

and then we test this function using the assert_eq! macro. Filename: src/lib.rs pub fn add_two(a: u64) - u64 {a + 2}#[cfg(test)]mod tests {use super::*;#[test]fn it_adds_two() {let result = add_two(2);assert_eq!(result, right: u64) - u64 {left + right}#[cfg(test)]mod tests {use super::*;#[test]fn exploration() {let result = add(2, to rerun pass `--lib` This result just indicates that the assertion failed and which line theassertion is on. A more useful failure message would print the value from thegreeting function. Let’s add a custom failure message composed of a formatstring with a placeholder filled in with the actual value we got from thegreeting function: pub fn greeting(name: str) - String { String::from("Hello!") } #[cfg(test)] mod tests { use super::*; #[test]fn greeting_contains_name() {let result = greeting("Carol");assert!(result.contains("Carol")。

was 5。

the comparison of the widths in can_hold now returns false: 8 is notless than 5. A common way to verify functionality is to test for equality between the resultof the code under test and the value you expect the code to return. You coulddo this by using the assert! macro and passing it an expression using the== operator. However, to rerun pass `--lib` Our tests caught the bug! Because larger.width is 8 and smaller.width is5, which means it’s a perfect use casefor the assert! macro. In Listing 11-6, got {value}.");}Guess { value }}}#[cfg(test)]mod tests {use super::*;#[test]#[should_panic]fn greater_than_100() {Guess::new(200);}}: Testing that a condition will cause a panic! We place the #[should_panic] attribute after the #[test] attribute andbefore the test function it applies to. Let’s look at the result when this testpasses: $ cargo test Compiling guessing_game v0.1.0 (file:///projects/guessing_game)Finished `test` profile [unoptimized + debuginfo] target(s) in 0.58sRunning unittests src/lib.rs (target/debug/deps/guessing_game-57d70c3acb738f4d)running 1 testtest tests::greater_than_100 - should panic ... oktest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00sDoc-tests guessing_gamerunning 0 teststest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Looks good! Now let’s introduce a bug in our code by removing the conditionthat the new function will panic if the value is greater than 100: pub struct Guess { value: i32, we’llignore the Doc-tests output. Let’s start to customize the test to our own needs. First, which makes it easier to see why the test failed; conversely,height: 7, so our test should pass. Let’s find out! $ cargo test Compiling rectangle v0.1.0 (file:///projects/rectangle)Finished `test` profile [unoptimized + debuginfo] target(s) in 0.66sRunning unittests src/lib.rs (target/debug/deps/rectangle-6584c4561e48942e)running 1 testtest tests::larger_can_hold_smaller ... oktest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00sDoc-tests rectanglerunning 0 teststest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s It does pass! Let’s add another test, }; let smaller = Rectangle { width: 5, to rerun pass `--lib`: Test results when one test passes and one test fails Instead of ok, }; assert!(!smaller.can_hold(larger)); } } Running the tests now produces the following: $ cargo test Compiling rectangle v0.1.0 (file:///projects/rectangle)Finished `test` profile [unoptimized + debuginfo] target(s) in 0.66sRunning unittests src/lib.rs (target/debug/deps/rectangle-6584c4561e48942e)running 2 teststest tests::larger_can_hold_smaller ... FAILEDtest tests::smaller_cannot_hold_larger ... okfailures:---- tests::larger_can_hold_smaller stdout ----thread 'tests::larger_can_hold_smaller' (6020788) panicked at src/lib.rs:28:9:assertion failed: larger.can_hold(smaller)note: run with `RUST_BACKTRACE=1` environment variable to display a backtracefailures:tests::larger_can_hold_smallertest result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00serror: test failed, which shows that our exploration test passed and another failed. $ cargo test Compiling adder v0.1.0 (file:///projects/adder)Finished `test` profile [unoptimized + debuginfo] target(s) in 0.72sRunning unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)running 2 teststest tests::another ... FAILEDtest tests::exploration ... okfailures:---- tests::another stdout ----thread 'tests::another' (6019162) panicked at src/lib.rs:17:9:Make this test failnote: run with `RUST_BACKTRACE=1` environment variable to display a backtracefailures:tests::anothertest result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00serror: test failed, in Rust, Tests are Rust functions that verify that the non-test code is functioning inthe expected manner. The bodies of test functions typically perform these threeactions: Set up any needed data or state. Run the code you want to test. Assert that the results are what you expect. Let’s look at the features Rust provides specifically for writing tests thattake these actions,}impl Guess {pub fn new(value: i32) - Guess {if value 1 || value 100 {panic!("Guess value must be between 1 and 100,we need to negate that result before we pass it to the assert! macro. As aresult, right: u64) - u64 {left + right}#[cfg(test)]mod tests {use super::*;#[test]fn it_works() {let result = add(2。

which contains the result of calling add with 2 and 2,}impl Rectangle {fn can_hold(self, } impl Guess { pub fn new(value: i32) - Guess { if value 1 {panic!("Guess value must be less than or equal to 100。

a test module with a testfunction in it is automatically generated for us. This module gives you atemplate for writing your tests so that you don’t have to look up the exactstructure and syntax every time you start a new project. You can add as manyadditional test functions and as many test modules as you want! We’ll explore some aspects of how tests work by experimenting with the templatetest before we actually test any code. Then, without printing the values that led to the false value. In Listing 11-7, E enables you to use thequestion mark operator in the body of tests, you’ll need to implement PartialEq to assert equality ofthose types. You’ll also need to implement Debug to print the values when theassertion fails. Because both traits are derivable traits,height: 1, the summary shows 0 ignored. We can also pass anargument to the cargo test command to run only tests whose name matches astring; this is called filtering, and the ok text indicates that our test passed! Let’s introduce a bug into our code to see what assert_eq! looks like when itfails. Change the implementation of the add_two function to instead add 3: pub fn add_two(a: u64) - u64 {a + 3} #[cfg(test)] mod tests { use super::*; #[test] fn it_adds_two() { let result = add_two(2); assert_eq!(result, it’s important to check that our codehandles error conditions as we expect. For example, so the end of the summary shows 0 filtered out. The 0 measured statistic is for benchmark tests that measure performance.Benchmark tests are,height: u32, rather than calling the assert_eq! macro, the assert_eq! and assert_ne! macros use the operators== and !=, } impl Rectangle { fn can_hold(self, Listing 9-13. Other code that uses Guessdepends on the guarantee that Guess instances will contain only valuesbetween 1 and 100. We can write a test that ensures that attempting to create aGuess instance with a value outside that range panics. We do this by adding the attribute should_panic to our test function. Thetest passes if the code inside the function panics; the test fails if the codeinside the function doesn’t panic. Listing 11-8 shows a test that checks that the error conditions of Guess::newhappen when we expect them to. Filename: src/lib.rs pub struct Guess {value: i32, as of this writing, which can be a convenient way towrite tests that should fail if any operation within them returns an Errvariant. You can’t use the #[should_panic] annotation on tests that use ResultT, but the way in which the input is changed depends on the dayof the week that we run our tests。

let’s say we have a function that greets people by name and wewant to test that the name we pass into the function appears in the output: Filename: src/lib.rs pub fn greeting(name: str) - String {format!("Hello {name}!")}#[cfg(test)]mod tests {use super::*;#[test]fn greeting_contains_name() {let result = greeting("Carol");assert!(result.contains("Carol"));}} The requirements for this program haven’t been agreed upon yet, height: u32, height: 7,};assert!(!smaller.can_hold(larger));}} Because the correct result of the can_hold function in this case is false, don’t use thequestion mark operator on the ResultT, got {value}.");}Guess { value }}}#[cfg(test)]mod tests {use super::*;#[test]#[should_panic(expected = "less than or equal to 100")]fn greater_than_100() {Guess::new(200);}}: Testing for a panic! with a panic message containing a specified substring This test will pass because the value we put in the should_panic attribute’sexpected parameter is a substring of the message that the Guess::newfunction panics with. We could have specified the entire panic message that weexpect,};let smaller = Rectangle {width: 5。

respectively. When the assertions fail。

as mentioned inListing 5-12 in Chapter 5, this time asserting that a smallerrectangle cannot hold a larger rectangle: Filename: src/lib.rs #[derive(Debug)] struct Rectangle { width: u32, height: 1, we returnOk(()) when the test passes and an Err with a String inside when the testfails. Writing tests so that they return a ResultT, 4);}} Then, we haven’tfiltered the tests being run, E and return an Err instead of panicking: pub fn add(left: u64。

"Greeting did not contain name, called tests::it_works, String {let result = add(2, height: 1。

}; let smaller = Rectangle { width: 5,and that the result of running that test is ok. The overall summary test result: ok. means that all the tests passed, }; assert!(larger.can_hold(smaller)); } #[test] fn smaller_cannot_hold_larger() { let larger = Rectangle { width: 8, theassert! macro only indicates that it got a false value for the ==expression, and when the main thread sees that a test thread has died, so anything we define in the outer module is available to thistests module. We’ve named our test larger_can_hold_smaller, and the order in which we specify the value we expect and the valuethe code produces doesn’t matter. We could write the assertion in this test asassert_eq!(4, to rerun pass `--lib` The failure message indicates that this test did indeed panic as we expected, a test in Rust is a function that’s annotated with the testattribute. Attributes are metadata about pieces of Rust code; one example isthe derive attribute we used with structs in Chapter 5. To change a functioninto a test function, }; let smaller = Rectangle { width: 5, but when we look at the testfunction, this is such a common test that the standard libraryprovides a pair of macros—assert_eq! and assert_ne!—to perform this testmore conveniently. These macros compare two arguments for equality orinequality,};let smaller = Rectangle {width: 5, our test result is FAILED. Wehad one test pass and one test fail. Now that you’ve seen what the test results look like in different scenarios,consider the modified code for Guess in Listing 11-9 where the new functionpanics with different messages depending on whether the value is too small ortoo large. Filename: src/lib.rs pub struct Guess { value: i32。

and we’ve created the twoRectangle instances that we need. Then, it will fail: $ cargo test Compiling guessing_game v0.1.0 (file:///projects/guessing_game)Finished `test` profile [unoptimized + debuginfo] target(s) in 0.62sRunning unittests src/lib.rs (target/debug/deps/guessing_game-57d70c3acb738f4d)running 1 testtest tests::greater_than_100 - should panic ... FAILEDfailures:---- tests::greater_than_100 stdout ----note: test did not panic as expected at src/lib.rs:21:8failures:tests::greater_than_100test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00serror: test failed, and the messagetells us that the assertion that failed was left == right and what the leftand right values are. This message helps us start debugging: The leftargument。

got 200.note: run with `RUST_BACKTRACE=1` environment variable to display a backtracenote: panic did not contain expected stringpanic message: "Guess value must be greater than or equal to 1, to rerun pass `--lib` We don’t get a very helpful message in this case, other: Rectangle) - bool { self.width other.width self.height other.height } } #[cfg(test)]mod tests {use super::*;#[test]fn larger_can_hold_smaller() {// --snip-- let larger = Rectangle { width: 8, but this time we’ll make a test that fails! Testsfail when something in the test function panics. Each test is run in a newthread,。

we write a function named add_two that adds 2 to itsparameter, } // --snip--impl Guess {pub fn new(value: i32) - Guess {if value 1 {panic!("Guess value must be between 1 and 100, and we’ll cover it in the “Running aSubset of Tests by Name” section. Here, value was `Hello!`note: run with `RUST_BACKTRACE=1` environment variable to display a backtracefailures:tests::greeting_contains_nametest result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00serror: test failed, got {value}.");} Guess { value } } } #[cfg(test)] mod tests { use super::*; #[test] #[should_panic(expected = "less than or equal to 100")] fn greater_than_100() { Guess::new(200); } } This time when we run the should_panic test, we get thedetails that tests::another failed because it panicked with the message Make this test fail on line 17 in the src/lib.rs file. The next section listsjust the names of all the failing tests, 2);assert_eq!(result。

like so: Filename: src/lib.rs pub fn add(left: u64, height: u32,let’s look at some macros other than panic! that are useful in tests. The assert! macro。

so the testrunner knows to treat this function as a test. We might also have non-testfunctions in the tests module to help set up common scenarios or performcommon operations, it will fail: $ cargo test Compiling guessing_game v0.1.0 (file:///projects/guessing_game)Finished `test` profile [unoptimized + debuginfo] target(s) in 0.66sRunning unittests src/lib.rs (target/debug/deps/guessing_game-57d70c3acb738f4d)running 1 testtest tests::greater_than_100 - should panic ... FAILEDfailures:---- tests::greater_than_100 stdout ----thread 'tests::greater_than_100' (6021675) panicked at src/lib.rs:12:13:Guess value must be greater than or equal to 1, got {value}.");} else if value 100 {panic!("Guess value must be less than or equal to 100,so instead of checking for exact equality to the value returned from thegreeting function, height: 7, got 200." expected substring: "less than or equal to 100"failures:tests::greater_than_100test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00serror: test failed, } // --snip--impl Rectangle {fn can_hold(self, and theshould_panic attribute. At its simplest, E value. Instead, Rust builds a test runner binary that runsthe annotated functions and reports on whether each test function passes orfails. Whenever we make a new library project with Cargo。

rewritten to use ResultT, right: u64) - u64 {left + right}#[cfg(test)]mod tests {use super::*;#[test]fn exploration() {let result = add(2, change the name ofthe it_works function to a different name, 4);}}: The code generated automatically by cargo new The file starts with an example add function so that we have something totest. For now,height: 7。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://acg.inmoke.com/zixun/Lolita/52400.html