]> git.proxmox.com Git - rustc.git/blob - src/doc/book/second-edition/src/ch11-00-testing.md
New upstream version 1.24.1+dfsg1
[rustc.git] / src / doc / book / second-edition / 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! Correctness in our programs is the
7 extent to which our code does what we intend it to do. Rust is a programming
8 language designed with a high degree of concern about the correctness of
9 programs, but correctness is complex and not easy to prove. Rust’s type system
10 shoulders a huge part of this burden, but the type system cannot catch every
11 kind of incorrectness. As such, Rust includes support for writing automated
12 software tests within the language.
13
14 As an example, say we write a function called `add_two` that adds two to
15 whatever number is passed to it. This function’s signature accepts an integer
16 as a parameter and returns an integer as a result. When we implement and
17 compile that function, Rust does all the type checking and borrow checking that
18 you’ve learned so far to ensure that, for instance, we aren’t passing a
19 `String` value or an invalid reference to this function. But Rust *can’t* check
20 that this function will do precisely what we intend, which is return the
21 parameter plus two rather than, say, the parameter plus 10 or the parameter
22 minus 50! That’s where tests come in.
23
24 We can write tests that assert, for example, that when we pass `3` to the
25 `add_two` function, the returned value is `5`. We can run these tests whenever
26 we make changes to our code to make sure any existing correct behavior has not
27 changed.
28
29 Testing is a complex skill: although we can’t cover every detail about how to
30 write good tests in one chapter, we’ll discuss the mechanics of Rust’s testing
31 facilities. We’ll talk about the annotations and macros available to you when
32 writing your tests, the default behavior and options provided for running your
33 tests, and how to organize tests into unit tests and integration tests.