]> git.proxmox.com Git - rustc.git/blob - src/doc/book/src/ch11-00-testing.md
7f11ec1494fe9fc5d6a4b14422059657fe041efa
[rustc.git] / src / doc / book / src / ch11-00-testing.md
1 # Writing Automated Tests
2
3 In his 1972 essay “The Humble Programmer,” Edsger W. Dijkstra said that
4 “Program testing can be a very effective way to show the presence of bugs, but
5 it is hopelessly inadequate for showing their absence.” That doesn’t mean we
6 shouldn’t try to test as much as we can!
7
8 Correctness in our programs is the extent to which our code does what we intend
9 it to do. Rust is designed with a high degree of concern about the correctness
10 of programs, but correctness is complex and not easy to prove. Rust’s type
11 system shoulders a huge part of this burden, but the type system cannot catch
12 everything. As such, Rust includes support for writing automated software tests.
13
14 Say we write a function `add_two` that adds 2 to whatever number is passed to
15 it. This function’s signature accepts an integer as a parameter and returns an
16 integer as a result. When we implement and compile that function, Rust does all
17 the type checking and borrow checking that you’ve learned so far to ensure
18 that, for instance, we aren’t passing a `String` value or an invalid reference
19 to this function. But Rust *can’t* check that this function will do precisely
20 what we intend, which is return the parameter plus 2 rather than, say, the
21 parameter plus 10 or the parameter minus 50! That’s where tests come in.
22
23 We can write tests that assert, for example, that when we pass `3` to the
24 `add_two` function, the returned value is `5`. We can run these tests whenever
25 we make changes to our code to make sure any existing correct behavior has not
26 changed.
27
28 Testing is a complex skill: although we can’t cover every detail about how to
29 write good tests in one chapter, we’ll discuss the mechanics of Rust’s testing
30 facilities. We’ll talk about the annotations and macros available to you when
31 writing your tests, the default behavior and options provided for running your
32 tests, and how to organize tests into unit tests and integration tests.