You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
trpl-zh-cn/docs/ch11-01-writing-tests.html

593 lines
41 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>编写测试 - Rust 程序设计语言 简体中文版</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="description" content="Rust 程序设计语言 简体中文版">
<meta name="viewport" content="width=device-width, initial-scale=1">
<base href="">
<link rel="stylesheet" href="book.css">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<link rel="shortcut icon" href="favicon.png">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel="stylesheet" href="highlight.css">
<link rel="stylesheet" href="tomorrow-night.css">
<!-- MathJax -->
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<!-- Fetch JQuery from CDN but have a local fallback -->
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
if (typeof jQuery == 'undefined') {
document.write(unescape("%3Cscript src='jquery.js'%3E%3C/script%3E"));
}
</script>
</head>
<body class="light">
<!-- Set the theme before any content is loaded, prevents flash -->
<script type="text/javascript">
var theme = localStorage.getItem('theme');
if (theme == null) { theme = 'light'; }
$('body').removeClass().addClass(theme);
</script>
<!-- Hide / unhide sidebar before it is displayed -->
<script type="text/javascript">
var sidebar = localStorage.getItem('sidebar');
if (sidebar === "hidden") { $("html").addClass("sidebar-hidden") }
else if (sidebar === "visible") { $("html").addClass("sidebar-visible") }
</script>
<div id="sidebar" class="sidebar">
<ul class="chapter"><li><a href="ch01-00-introduction.html"><strong>1.</strong> 介绍</a></li><li><ul class="section"><li><a href="ch01-01-installation.html"><strong>1.1.</strong> 安装</a></li><li><a href="ch01-02-hello-world.html"><strong>1.2.</strong> Hello, World!</a></li></ul></li><li><a href="ch02-00-guessing-game-tutorial.html"><strong>2.</strong> 猜猜看教程</a></li><li><a href="ch03-00-common-programming-concepts.html"><strong>3.</strong> 通用编程概念</a></li><li><ul class="section"><li><a href="ch03-01-variables-and-mutability.html"><strong>3.1.</strong> 变量和可变性</a></li><li><a href="ch03-02-data-types.html"><strong>3.2.</strong> 数据类型</a></li><li><a href="ch03-03-how-functions-work.html"><strong>3.3.</strong> 函数如何工作</a></li><li><a href="ch03-04-comments.html"><strong>3.4.</strong> 注释</a></li><li><a href="ch03-05-control-flow.html"><strong>3.5.</strong> 控制流</a></li></ul></li><li><a href="ch04-00-understanding-ownership.html"><strong>4.</strong> 认识所有权</a></li><li><ul class="section"><li><a href="ch04-01-what-is-ownership.html"><strong>4.1.</strong> 什么是所有权</a></li><li><a href="ch04-02-references-and-borrowing.html"><strong>4.2.</strong> 引用 &amp; 借用</a></li><li><a href="ch04-03-slices.html"><strong>4.3.</strong> Slices</a></li></ul></li><li><a href="ch05-00-structs.html"><strong>5.</strong> 结构体</a></li><li><ul class="section"><li><a href="ch05-01-method-syntax.html"><strong>5.1.</strong> 方法语法</a></li></ul></li><li><a href="ch06-00-enums.html"><strong>6.</strong> 枚举和模式匹配</a></li><li><ul class="section"><li><a href="ch06-01-defining-an-enum.html"><strong>6.1.</strong> 定义枚举</a></li><li><a href="ch06-02-match.html"><strong>6.2.</strong> <code>match</code>控制流运算符</a></li><li><a href="ch06-03-if-let.html"><strong>6.3.</strong> <code>if let</code>简单控制流</a></li></ul></li><li><a href="ch07-00-modules.html"><strong>7.</strong> 模块</a></li><li><ul class="section"><li><a href="ch07-01-mod-and-the-filesystem.html"><strong>7.1.</strong> <code>mod</code>和文件系统</a></li><li><a href="ch07-02-controlling-visibility-with-pub.html"><strong>7.2.</strong> 使用<code>pub</code>控制可见性</a></li><li><a href="ch07-03-importing-names-with-use.html"><strong>7.3.</strong> 使用<code>use</code>导入命名</a></li></ul></li><li><a href="ch08-00-common-collections.html"><strong>8.</strong> 通用集合类型</a></li><li><ul class="section"><li><a href="ch08-01-vectors.html"><strong>8.1.</strong> vector</a></li><li><a href="ch08-02-strings.html"><strong>8.2.</strong> 字符串</a></li><li><a href="ch08-03-hash-maps.html"><strong>8.3.</strong> 哈希 map</a></li></ul></li><li><a href="ch09-00-error-handling.html"><strong>9.</strong> 错误处理</a></li><li><ul class="section"><li><a href="ch09-01-unrecoverable-errors-with-panic.html"><strong>9.1.</strong> <code>panic!</code>与不可恢复的错误</a></li><li><a href="ch09-02-recoverable-errors-with-result.html"><strong>9.2.</strong> <code>Result</code>与可恢复的错误</a></li><li><a href="ch09-03-to-panic-or-not-to-panic.html"><strong>9.3.</strong> <code>panic!</code>还是不<code>panic!</code></a></li></ul></li><li><a href="ch10-00-generics.html"><strong>10.</strong> 泛型、trait 和生命周期</a></li><li><ul class="section"><li><a href="ch10-01-syntax.html"><strong>10.1.</strong> 泛型数据类型</a></li><li><a href="ch10-02-traits.html"><strong>10.2.</strong> trait定义共享的行为</a></li><li><a href="ch10-03-lifetime-syntax.html"><strong>10.3.</strong> 生命周期与引用有效性</a></li></ul></li><li><a href="ch11-00-testing.html"><strong>11.</strong> 测试</a></li><li><ul class="section"><li><a href="ch11-01-writing-tests.html" class="active"><strong>11.1.</strong> 编写测试</a></li><li><a href="ch11-02-running-tests.html"><strong>11.2.</strong> 运行测试</a></li><li><a href="ch11-03-test-organization.html"><strong>11.3.</strong> 测试的组织结构</a></li></ul></li><li><a href="ch12-00-an-io-project.html"><strong>12.</strong> 一个 I/O 项目</a></li><li><ul class="section"><li><a href="ch12-01-accepting-command-line-arguments.html"><strong>12.1.</strong> 接受命令行参数</a></li><li><a href="ch12-02-reading-a-file.html"><strong>12.2.</strong> 读取文件</a></li><li><a href="ch12-03-improving-error-handling-and-modularity.html"><strong>12.3.</strong> 增强错误处理和模块化</a></li><li><a href="ch12-04-testing-the-librarys-functionality.html"><strong>12.4.</strong> 测试库的功能</a></li><li><a href="ch12-05-working-with-environment-variables.html"><strong>12.5.</strong> 处理环境变量</a></li><li><a href="ch12-06-writing-to-stderr-instead-of-stdout.html"><strong>12.6.</strong> 输出到<code>stderr</code>而不是<code>stdout</code></a></li></ul></li><li><a href="ch13-00-functional-features.html"><strong>13.</strong> Rust 中的函数式语言功能</a></li><li><ul class="section"><li><a href="ch13-01-closures.html"><strong>13.1.</strong> 闭包</a></li><li><a href="ch13-02-iterators.html"><strong>13.2.</strong> 迭代器</a></li><li><a href="ch13-03-improving-our-io-project.html"><strong>13.3.</strong> 改进 I/O 项目</a></li><li><a href="ch13-04-performance.html"><strong>13.4.</strong> 性能</a></li></ul></li><li><a href="ch14-00-more-about-cargo.html"><strong>14.</strong> 更多关于 Cargo 和 Crates.io</a></li><li><ul class="section"><li><a href="ch14-01-release-profiles.html"><strong>14.1.</strong> 发布配置</a></li><li><a href="ch14-02-publishing-to-crates-io.html"><strong>14.2.</strong> 将 crate 发布到 Crates.io</a></li><li><a href="ch14-03-cargo-workspaces.html"><strong>14.3.</strong> Cargo 工作空间</a></li><li><a href="ch14-04-installing-binaries.html"><strong>14.4.</strong> 使用<code>cargo install</code>从 Crates.io 安装文件</a></li><li><a href="ch14-05-extending-cargo.html"><strong>14.5.</strong> Cargo 自定义扩展命令</a></li></ul></li><li><a href="ch15-00-smart-pointers.html"><strong>15.</strong> 智能指针</a></li><li><ul class="section"><li><a href="ch15-01-box.html"><strong>15.1.</strong> <code>Box&lt;T&gt;</code>用于已知大小的堆上数据</a></li><li><a href="ch15-02-deref.html"><strong>15.2.</strong> <code>Deref</code> Trait 允许通过引用访问数据</a></li><li><a href="ch15-03-drop.html"><strong>15.3.</strong> <code>Drop</code> Trait 运行清理代码</a></li><li><a href="ch15-04-rc.html"><strong>15.4.</strong> <code>Rc&lt;T&gt;</code> 引用计数智能指针</a></li><li><a href="ch15-05-interior-mutability.html"><strong>15.5.</strong> <code>RefCell&lt;T&gt;</code>和内部可变性模式</a></li><li><a href="ch15-06-reference-cycles.html"><strong>15.6.</strong> 引用循环和内存泄漏是安全的</a></li></ul></li><li><a href="ch16-00-concurrency.html"><strong>16.</strong> 无畏并发</a></li><li><ul class="section"><li><a href="ch16-01-threads.html"><strong>16.1.</strong> 线程</a></li><li><a href="ch16-02-message-passing.html"><strong>16.2.</strong> 消息传递</a></li><li><a href="ch16-03-shared-state.html"><strong>16.3.</strong> 共享状态</a></li><li><a href="ch16-04-extensible-concurrency-sync-and-send.html"><strong>16.4.</strong> 可扩展的并发:<code>Sync</code><code>Send</code></a></li></ul></li><li><a href="ch17-00-oop.html"><strong>17.</strong> 面向对象</a></li><li><ul class="section"><li><a href="ch17-01-what-is-oo.html"><strong>17.1.</strong> 什么是面向对象</a></li></ul></li></ul>
</div>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar" class="menu-bar">
<div class="left-buttons">
<i id="sidebar-toggle" class="fa fa-bars"></i>
<i id="theme-toggle" class="fa fa-paint-brush"></i>
</div>
<h1 class="menu-title">Rust 程序设计语言 简体中文版</h1>
<div class="right-buttons">
<i id="print-button" class="fa fa-print" title="Print this book"></i>
</div>
</div>
<div id="content" class="content">
<a class="header" href="#编写测试" name="编写测试"><h2>编写测试</h2></a>
<blockquote>
<p><a href="https://github.com/rust-lang/book/blob/master/second-edition/src/ch11-01-writing-tests.md">ch11-01-writing-tests.md</a>
<br>
commit 55b294f20fc846a13a9be623bf322d8b364cee77</p>
</blockquote>
<p>测试用来验证非测试的代码按照期望的方式运行的 Rust 函数。测试函数体通常包括一些设置,运行需要测试的代码,接着断言其结果是我们所期望的。让我们看看 Rust 提供的具体用来编写测试的功能:<code>test</code>属性、一些宏和<code>should_panic</code>属性。</p>
<a class="header" href="#测试函数剖析" name="测试函数剖析"><h3>测试函数剖析</h3></a>
<p>作为最简单例子Rust 中的测试就是一个带有<code>test</code>属性注解的函数。属性attribute是关于 Rust 代码片段的元数据:第五章中结构体中用到的<code>derive</code>属性就是一个例子。为了将一个函数变成测试函数,需要在<code>fn</code>行之前加上<code>#[test]</code>。当使用<code>cargo test</code>命令运行测试函数时Rust 会构建一个测试执行者二进制文件用来运行标记了<code>test</code>属性的函数并报告每一个测试是通过还是失败。</p>
<!-- is it annotated with `test` by the user, or only automatically? I think
it's the latter, and has edited with a more active tone to make that clear, but
please change if I'm wrong -->
<!-- What do you mean by "only automatically"? The reader should be typing in
`#[test] on their own when they add new test functions; there's nothing special
about that text. I'm not sure what part of this chapter implied "only
automatically", can you point out where that's happening if we haven't taken
care of it? /Carol -->
<p>第七章当使用 Cargo 新建一个库项目时,它会自动为我们生成一个测试模块和一个测试函数。这有助于我们开始编写测试,因为这样每次开始新项目时不必去查找测试函数的具体结构和语法了。同时可以额外增加任意多的测试函数以及测试模块!</p>
<p>我们将先通过对自动生成的测试模板做一些试验来探索测试如何工作的一些方面内容,而不实际测试任何代码。接着会写一些真实的测试来调用我们编写的代码并断言他们的行为是正确的。</p>
<p>让我们创建一个新的库项目<code>adder</code></p>
<pre><code>$ cargo new adder
Created library `adder` project
$ cd adder
</code></pre>
<p>adder 库中<code>src/lib.rs</code>的内容应该看起来像这样:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">#[cfg(test)]
mod tests {
#[test]
fn it_works() {
}
}
</code></pre>
<p><span class="caption">Listing 11-1: The test module and function generated
automatically for us by <code>cargo new</code> </span></p>
<p>现在让我们暂时忽略<code>tests</code>模块和<code>#[cfg(test)]</code>注解并只关注函数。注意<code>fn</code>行之前的<code>#[test]</code>:这个属性表明这是一个测试函数,这样测试执行者就知道将其作为测试处理。也可以在<code>tests</code>模块中拥有非测试的函数来帮助我们建立通用场景或进行常见操作,所以需要使用<code>#[test]</code>属性标明哪些函数是测试。</p>
<p>这个函数目前没有任何内容,这意味着没有代码会使测试失败;一个空的测试是可以通过的!让我们运行一下看看它是否通过了。</p>
<p><code>cargo test</code>命令会运行项目中所有的测试,如列表 11-2 所示:</p>
<pre><code>$ cargo test
Compiling adder v0.1.0 (file:///projects/adder)
Finished debug [unoptimized + debuginfo] target(s) in 0.22 secs
Running target/debug/deps/adder-ce99bcc2479f4607
running 1 test
test tests::it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p><span class="caption">Listing 11-2: The output from running the one
automatically generated test </span></p>
<p>Cargo 编译并运行了测试。在<code>Compiling</code><code>Finished</code><code>Running</code>这几行之后,可以看到<code>running 1 test</code>这一行。下一行显示了生成的测试函数的名称,它是<code>it_works</code>,以及测试的运行结果,<code>ok</code>。接着可以看到全体测试运行结果的总结:<code>test result: ok.</code>意味着所有测试都通过了。<code>1 passed; 0 failed</code>表示通过或失败的测试数量。</p>
<p>这里并没有任何被标记为忽略的测试,所以总结表明<code>0 ignored</code>。在下一部分关于运行测试的不同方式中会讨论忽略测试。<code>0 measured</code>统计是针对测试性能的性能测试的。性能测试benchmark tests在编写本书时仍只属于开发版 Rustnightly Rust。请查看附录 D 来了解更多开发版 Rust 的信息。</p>
<p>测试输出中以<code>Doc-tests adder</code>开头的下一部分是所有文档测试的结果。现在并没有任何文档测试,不过 Rust 会编译任何出现在 API 文档中的代码示例。这个功能帮助我们使文档和代码保持同步!在第十四章的“文档注释”部分会讲到如何编写文档测试。现在我们将忽略<code>Doc-tests</code>部分的输出。</p>
<!-- I might suggest changing the name of the function, could be misconstrued
as part of the test output! -->
<!-- `it_works` is always the name that `cargo new` generates for the first
test function, though. We wanted to show the reader what happens when you run
the tests immediately after generating a new project; they pass without you
needing to change anything. I've added a bit to walk through changing the
function name and seeing how the output changes; I hope that's sufficient.
/Carol -->
<p>让我们改变测试的名称并看看这如何改变测试的输出。给<code>it_works</code>函数起个不同的名字,比如<code>exploration</code>,像这样:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">#[cfg(test)]
mod tests {
#[test]
fn exploration() {
}
}
</code></pre>
<p>并再次运行<code>cargo test</code>。现在输出中将出现<code>exploration</code>而不是<code>it_works</code></p>
<pre><code>running 1 test
test tests::exploration ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>让我们增加另一个测试,不过这一次是一个会失败的测试!当测试函数中出现 panic 时测试就失败了。第九章讲到了最简单的造成 panic 的方法:调用<code>panic!</code>宏!写入新函数后 <code>src/lib.rs</code> 现在看起来如列表 11-3 所示:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">#[cfg(test)]
mod tests {
#[test]
fn exploration() {
}
#[test]
fn another() {
panic!(&quot;Make this test fail&quot;);
}
}
</code></pre>
<p><span class="caption">Listing 11-3: Adding a second test; one that will fail
since we call the <code>panic!</code> macro </span></p>
<p>再次<code>cargo test</code>运行测试。输出应该看起来像列表 11-4它表明<code>exploration</code>测试通过了而<code>another</code>失败了:</p>
<pre><code class="language-text">running 2 tests
test tests::exploration ... ok
test tests::another ... FAILED
failures:
---- tests::another stdout ----
thread 'tests::another' panicked at 'Make this test fail', src/lib.rs:9
note: Run with `RUST_BACKTRACE=1` for a backtrace.
failures:
tests::another
test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured
error: test failed
</code></pre>
<p><span class="caption">Listing 11-4: Test results when one test passes and one
test fails </span></p>
<p><code>test tests::another</code>这一行是<code>FAILED</code>而不是<code>ok</code>了。在单独测试结果和总结之间多了两个新的部分:第一个部分显示了测试失败的详细原因。在这个例子中,<code>another</code>因为<code>panicked at 'Make this test fail'</code>而失败,这位于 <em>src/lib.rs</em> 的第 9 行。下一部分仅仅列出了所有失败的测试,这在很有多测试和很多失败测试的详细输出时很有帮助。可以使用失败测试的名称来只运行这个测试,这样比较方便调试;下一部分会讲到更多运行测试的方法。</p>
<p>最后是总结行:总体上讲,一个测试结果是<code>FAILED</code>的。有一个测试通过和一个测试失败。</p>
<p>现在我们见过不同场景中测试结果是什么样子的了,再来看看除了<code>panic!</code>之外一些在测试中有帮助的宏吧。</p>
<a class="header" href="#使用assert宏来检查结果" name="使用assert宏来检查结果"><h3>使用<code>assert!</code>宏来检查结果</h3></a>
<p><code>assert!</code>宏由标准库提供,在希望确保测试中一些条件为<code>true</code>时非常有用。需要向<code>assert!</code>宏提供一个计算为布尔值的参数。如果值是<code>true</code><code>assert!</code>什么也不做同时测试会通过。如果值为<code>false</code><code>assert!</code>调用<code>panic!</code>宏,这会导致测试失败。这是一个帮助我们检查代码是否以期望的方式运行的宏。</p>
<!-- what kind of thing can be passed as an argument? Presumably when we use it
for real we won't pass it `true` or `false` as an argument, but some condition
that will evaluate to true or false? In which case, should below be phrased "If
the argument evaluates to true" and an explanation of that? Or maybe even a
working example would be better, this could be misleading -->
<!-- We were trying to really break it down, to show just how the `assert!`
macro works and what it looks like for it to pass or fail, before we got into
calling actual code. We've changed this section to move a bit faster and just
write actual tests instead. /Carol -->
<p>回忆一下第五章中,列表 5-9 中有一个<code>Rectangle</code>结构体和一个<code>can_hold</code>方法,在列表 11-5 中再次使用他们。将他们放进 <em>src/lib.rs</em> 而不是 <em>src/main.rs</em> 并使用<code>assert!</code>宏编写一些测试。</p>
<!-- Listing 5-9 wasn't marked as such; I'll fix it the next time I get Chapter
5 for editing. /Carol -->
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">#[derive(Debug)]
pub struct Rectangle {
length: u32,
width: u32,
}
impl Rectangle {
pub fn can_hold(&amp;self, other: &amp;Rectangle) -&gt; bool {
self.length &gt; other.length &amp;&amp; self.width &gt; other.width
}
}
</code></pre>
<p><span class="caption">Listing 11-5: The <code>Rectangle</code> struct and its <code>can_hold</code>
method from Chapter 5 </span></p>
<p><code>can_hold</code>方法返回一个布尔值,这意味着它完美符合<code>assert!</code>宏的使用场景。在列表 11-6 中,让我们编写一个<code>can_hold</code>方法的测试来作为练习,这里创建一个长为 8 宽为 7 的<code>Rectangle</code>实例并假设它可以放得下另一个长为5 宽为 1 的<code>Rectangle</code>实例:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">#[cfg(test)]
mod tests {
use super::*;
#[test]
fn larger_can_hold_smaller() {
let larger = Rectangle { length: 8, width: 7 };
let smaller = Rectangle { length: 5, width: 1 };
assert!(larger.can_hold(&amp;smaller));
}
}
</code></pre>
<p><span class="caption">Listing 11-6: A test for <code>can_hold</code> that checks that a
larger rectangle indeed holds a smaller rectangle </span></p>
<p>注意在<code>tests</code>模块中新增加了一行:<code>use super::*;</code><code>tests</code>是一个普通的模块,它遵循第七章介绍的通常的可见性规则。因为这是一个内部模块,需要将外部模块中被测试的代码引入到内部模块的作用域中。这里选择使用全局导入使得外部模块定义的所有内容在<code>tests</code>模块中都是可用的。</p>
<p>我们将测试命名为<code>larger_can_hold_smaller</code>,并创建所需的两个<code>Rectangle</code>实例。接着调用<code>assert!</code>宏并传递<code>larger.can_hold(&amp;smaller)</code>调用的结果作为参数。这个表达式预期会返回<code>true</code>,所以测试应该通过。让我们拭目以待!</p>
<pre><code>running 1 test
test tests::larger_can_hold_smaller ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>它确实通过了!再来增加另一个测试,这一回断言一个更小的矩形不能放下一个更大的矩形:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">#[cfg(test)]
mod tests {
use super::*;
#[test]
fn larger_can_hold_smaller() {
let larger = Rectangle { length: 8, width: 7 };
let smaller = Rectangle { length: 5, width: 1 };
assert!(larger.can_hold(&amp;smaller));
}
#[test]
fn smaller_can_hold_larger() {
let larger = Rectangle { length: 8, width: 7 };
let smaller = Rectangle { length: 5, width: 1 };
assert!(!smaller.can_hold(&amp;larger));
}
}
</code></pre>
<p>因为这里<code>can_hold</code>函数的正确结果是<code>false</code>,我们需要将这个结果取反后传递给<code>assert!</code>宏。这样的话,测试就会通过而<code>can_hold</code>将返回<code>false</code></p>
<pre><code>running 2 tests
test tests::smaller_can_hold_larger ... ok
test tests::larger_can_hold_smaller ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>这个通过的测试!现在让我们看看如果引入一个 bug 的话测试结果会发生什么。将<code>can_hold</code>方法中比较长度时本应使用大于号的地方改成小于号:</p>
<pre><code class="language-rust">#[derive(Debug)]
pub struct Rectangle {
length: u32,
width: u32,
}
impl Rectangle {
pub fn can_hold(&amp;self, other: &amp;Rectangle) -&gt; bool {
self.length &lt; other.length &amp;&amp; self.width &gt; other.width
}
}
</code></pre>
<p>现在运行测试会产生:</p>
<pre><code>running 2 tests
test tests::smaller_can_hold_larger ... ok
test tests::larger_can_hold_smaller ... FAILED
failures:
---- tests::larger_can_hold_smaller stdout ----
thread 'tests::larger_can_hold_smaller' panicked at 'assertion failed:
larger.can_hold(&amp;smaller)', src/lib.rs:22
note: Run with `RUST_BACKTRACE=1` for a backtrace.
failures:
tests::larger_can_hold_smaller
test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured
</code></pre>
<p>我们的测试捕获了 bug因为<code>larger.length</code>是 8 而<code>smaller.length</code> 是 5<code>can_hold</code>中的长度比较现在返回<code>false</code>因为 8 不小于 5。</p>
<a class="header" href="#使用assert_eq和assert_ne宏来测试相等" name="使用assert_eq和assert_ne宏来测试相等"><h3>使用<code>assert_eq!</code><code>assert_ne!</code>宏来测试相等</h3></a>
<p>测试功能的一个常用方法是将需要测试代码的值与期望值做比较,并检查是否相等。可以通过向<code>assert!</code>宏传递一个使用<code>==</code>宏的表达式来做到。不过这个操作实在是太常见了,以至于标注库提供了一对宏来方便处理这些操作:<code>assert_eq!</code><code>assert_ne!</code>。这两个宏分别比较两个值是相等还是不相等。当断言失败时他们也会打印出这两个值具体是什么,以便于观察测试<strong>为什么</strong>失败,而<code>assert!</code>只会打印出它从<code>==</code>表达式中得到了<code>false</code>值,而不是导致<code>false</code>值的原因。</p>
<p>列表 11-7 中,让我们编写一个对其参数加二并返回结果的函数<code>add_two</code>。接着使用<code>assert_eq!</code>宏测试这个函数:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">pub fn add_two(a: i32) -&gt; i32 {
a + 2
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_adds_two() {
assert_eq!(4, add_two(2));
}
}
</code></pre>
<p><span class="caption">Listing 11-7: Testing the function <code>add_two</code> using the
<code>assert_eq!</code> macro </span></p>
<p>测试通过了!</p>
<pre><code>running 1 test
test tests::it_adds_two ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>传递给<code>assert_eq!</code>宏的第一个参数4等于调用<code>add_two(2)</code>的结果。我们将会看到这个测试的那一行说<code>test tests::it_adds_two ... ok</code><code>ok</code>表明测试通过了!</p>
<p>在代码中引入一个 bug 来看看使用<code>assert_eq!</code>的测试失败是什么样的。修改<code>add_two</code>函数的实现使其加 3</p>
<pre><code class="language-rust">pub fn add_two(a: i32) -&gt; i32 {
a + 3
}
</code></pre>
<p>再次运行测试:</p>
<pre><code>running 1 test
test tests::it_adds_two ... FAILED
failures:
---- tests::it_adds_two stdout ----
thread 'tests::it_adds_two' panicked at 'assertion failed: `(left ==
right)` (left: `4`, right: `5`)', src/lib.rs:11
note: Run with `RUST_BACKTRACE=1` for a backtrace.
failures:
tests::it_adds_two
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured
</code></pre>
<p>测试捕获到了 bug<code>it_adds_two</code>测试失败并显示信息<code>assertion failed: `(left == right)` (left: `4`, right: `5`)</code>。这个信息有助于我们开始调试:它说<code>assert_eq!</code><code>left</code>参数是 4<code>right</code>参数,也就是<code>add_two(2)</code>的结果,是 5。</p>
<p>注意在一些语言和测试框架中,断言两个值相等的函数的参数叫做<code>expected</code><code>actual</code>,而且指定参数的顺序是需要注意的。然而在 Rust 中,他们则叫做<code>left</code><code>right</code>,同时指定期望的值和被测试代码产生的值的顺序并不重要。这个测试中的断言也可以写成<code>assert_eq!(add_two(2), 4)</code>,这时错误信息会变成<code>assertion failed: `(left == right)` (left: `5`, right: `4`)</code></p>
<p><code>assert_ne!</code>宏在传递给它的两个值不相等时通过而在相等时失败。这个宏在代码按照我们期望运行时不确定值<strong>应该</strong>是什么,不过知道他们绝对<strong>不应该</strong>是什么的时候最有用处。例如,如果一个函数确定会以某种方式改变其输出,不过这种方式由运行测试是星期几来决定,这时最好的断言可能就是函数的输出不等于其输入。</p>
<p><code>assert_eq!</code><code>assert_ne!</code>宏在底层分别使用了<code>==</code><code>!=</code>。当断言失败时,这些宏会使用调试格式打印出其参数,这意味着被比较的值必需实现了<code>PartialEq</code><code>Debug</code> trait。所有的基本类型和大部分标准库类型都实现了这些 trait。对于自定义的结构体和枚举需要实现 <code>PartialEq</code>才能断言他们的值是否相等。需要实现 <code>Debug</code>才能在断言失败时打印他们的值。因为这两个 trait 都是可推导 trait如第五章所提到的通常可以直接在结构体或枚举上添加<code>#[derive(PartialEq, Debug)]</code>注解。附录 C 中有更多关于这些和其他可推导 trait 的详细信息。</p>
<a class="header" href="#自定义错误信息" name="自定义错误信息"><h3>自定义错误信息</h3></a>
<p>也可以向<code>assert!</code><code>assert_eq!</code><code>assert_ne!</code>宏传递一个可选的参数来增加用于打印的自定义错误信息。任何在<code>assert!</code>必需的一个参数和<code>assert_eq!</code><code>assert_ne!</code>必需的两个参数之后指定的参数都会传递给第八章讲到的<code>format!</code>宏,所以可以传递一个包含<code>{}</code>占位符的格式字符串和放入占位符的值。自定义信息有助于记录断言的意义,这样到测试失败时,就能更好的例子代码出了什么问题。</p>
<p>例如,比如说有一个根据人名进行问候的函数,而我们希望测试将传递给函数的人名显示在输出中:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">pub fn greeting(name: &amp;str) -&gt; String {
format!(&quot;Hello {}!&quot;, name)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn greeting_contains_name() {
let result = greeting(&quot;Carol&quot;);
assert!(result.contains(&quot;Carol&quot;));
}
}
</code></pre>
<p>这个程序的需求还没有被确定,而我们非常确定问候开始的<code>Hello</code>文本不会改变。我们决定并不想在人名改变时
不得不更新测试,所以相比检查<code>greeting</code>函数返回的确切的值,我们将仅仅断言输出的文本中包含输入参数。</p>
<p>让我们通过改变<code>greeting</code>不包含<code>name</code>来在代码中引入一个 bug 来测试失败时是怎样的,</p>
<pre><code class="language-rust">pub fn greeting(name: &amp;str) -&gt; String {
String::from(&quot;Hello!&quot;)
}
</code></pre>
<p>运行测试会产生:</p>
<pre><code class="language-text">running 1 test
test tests::greeting_contains_name ... FAILED
failures:
---- tests::greeting_contains_name stdout ----
thread 'tests::greeting_contains_name' panicked at 'assertion failed:
result.contains(&quot;Carol&quot;)', src/lib.rs:12
note: Run with `RUST_BACKTRACE=1` for a backtrace.
failures:
tests::greeting_contains_name
</code></pre>
<p>这仅仅告诉了我们断言失败了和失败的行号。一个更有用的错误信息应该打印出从<code>greeting</code>函数得到的值。让我们改变测试函数来使用一个由包含占位符的格式字符串和从<code>greeting</code>函数取得的值组成的自定义错误信息:</p>
<pre><code class="language-rust,ignore">#[test]
fn greeting_contains_name() {
let result = greeting(&quot;Carol&quot;);
assert!(
result.contains(&quot;Carol&quot;),
&quot;Greeting did not contain name, value was `{}`&quot;, result
);
}
</code></pre>
<p>现在如果再次运行测试,将会看到更有价值的错误信息:</p>
<pre><code>---- tests::greeting_contains_name stdout ----
thread 'tests::greeting_contains_name' panicked at 'Result did not contain
name, value was `Hello`', src/lib.rs:12
note: Run with `RUST_BACKTRACE=1` for a backtrace.
</code></pre>
<p>可以在测试输出中看到所取得的确切的值,这会帮助我们理解发生了什么而不是期望发生什么。</p>
<a class="header" href="#使用should_panic检查-panic" name="使用should_panic检查-panic"><h3>使用<code>should_panic</code>检查 panic</h3></a>
<p>除了检查代码是否返回期望的正确的值之外,检查代码是否按照期望处理错误情况也是很重要的。例如,考虑第九章列表 9-8 创建的<code>Guess</code>类型。其他使用<code>Guess</code>的代码依赖于<code>Guess</code>实例只会包含 1 到 100 的值的保证。可以编写一个测试来确保创建一个超出范围的值的<code>Guess</code>实例会 panic。</p>
<p>可以通过对函数增加另一个属性<code>should_panic</code>来实现这些。这个属性在函数中的代码 panic 时会通过,而在其中的代码没有 panic 时失败。</p>
<p>列表 11-8 展示了如何编写一个测试来检查<code>Guess::new</code>按照我们的期望出现的错误情况:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">struct Guess {
value: u32,
}
impl Guess {
pub fn new(value: u32) -&gt; Guess {
if value &lt; 1 || value &gt; 100 {
panic!(&quot;Guess value must be between 1 and 100, got {}.&quot;, value);
}
Guess {
value: value,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic]
fn greater_than_100() {
Guess::new(200);
}
}
</code></pre>
<p><span class="caption">Listing 11-8: Testing that a condition will cause a
<code>panic!</code> </span></p>
<p><code>#[should_panic]</code>属性位于<code>#[test]</code>之后和对应的测试函数之前。让我们看看测试通过时它时什么样子:</p>
<pre><code>running 1 test
test tests::greater_than_100 ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>看起来不错!现在在代码中引入 bug通过移除<code>new</code>函数在值大于 100 时会 panic 的条件:</p>
<pre><code class="language-rust"># struct Guess {
# value: u32,
# }
#
impl Guess {
pub fn new(value: u32) -&gt; Guess {
if value &lt; 1 {
panic!(&quot;Guess value must be between 1 and 100, got {}.&quot;, value);
}
Guess {
value: value,
}
}
}
</code></pre>
<p>如果运行列表 11-8 的测试,它会失败:</p>
<pre><code>running 1 test
test tests::greater_than_100 ... FAILED
failures:
failures:
tests::greater_than_100
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured
</code></pre>
<p>这回并没有得到非常有用的信息,不过一旦我们观察测试函数,会发现它标注了<code>#[should_panic]</code>。这个错误意味着代码中函数<code>Guess::new(200)</code>并没有产生 panic。</p>
<p>然而<code>should_panic</code>测试可能是非常含糊不清的,因为他们只是告诉我们代码并没有产生 panic。<code>should_panic</code>甚至在测试因为其他不同的原因而不是我们期望发生的那个而 panic 时也会通过。为了使<code>should_panic</code>测试更精确,可以给<code>should_panic</code>属性增加一个可选的<code>expected</code>参数。测试工具会确保错误信息中包含其提供的文本。例如,考虑列表 11-9 中修改过的<code>Guess</code>,这里<code>new</code>函数更具其值是过大还或者过小而提供不同的 panic 信息:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">struct Guess {
value: u32,
}
impl Guess {
pub fn new(value: u32) -&gt; Guess {
if value &lt; 1 {
panic!(&quot;Guess value must be greater than or equal to 1, got {}.&quot;,
value);
} else if value &gt; 100 {
panic!(&quot;Guess value must be less than or equal to 100, got {}.&quot;,
value);
}
Guess {
value: value,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic(expected = &quot;Guess value must be less than or equal to 100&quot;)]
fn greater_than_100() {
Guess::new(200);
}
}
</code></pre>
<p><span class="caption">Listing 11-9: Testing that a condition will cause a
<code>panic!</code> with a particular panic message </span></p>
<p>这个测试会通过,因为<code>should_panic</code>属性中<code>expected</code>参数提供的值是<code>Guess::new</code>函数 panic 信息的子字符串。我们可以指定期望的整个 panic 信息,在这个例子中是<code>Guess value must be less than or equal to 100, got 200.</code>。这依赖于 panic 有多独特或动态和你希望测试有多准确。在这个例子中,错误信息的子字符串足以确保函数在<code>else if value &gt; 100</code>的情况下运行。</p>
<p>为了观察带有<code>expected</code>信息的<code>should_panic</code>测试失败时会发生什么,让我们再次引入一个 bug 来将<code>if value &lt; 1</code><code>else if value &gt; 100</code>的代码块对换:</p>
<pre><code class="language-rust,ignore">if value &lt; 1 {
panic!(&quot;Guess value must be less than or equal to 100, got {}.&quot;, value);
} else if value &gt; 100 {
panic!(&quot;Guess value must be greater than or equal to 1, got {}.&quot;, value);
}
</code></pre>
<p>这一次运行<code>should_panic</code>测试,它会失败:</p>
<pre><code>running 1 test
test tests::greater_than_100 ... FAILED
failures:
---- tests::greater_than_100 stdout ----
thread 'tests::greater_than_100' panicked at 'Guess value must be greater
than or equal to 1, got 200.', src/lib.rs:10
note: Run with `RUST_BACKTRACE=1` for a backtrace.
note: Panic did not include expected string 'Guess value must be less than or
equal to 100'
failures:
tests::greater_than_100
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured
</code></pre>
<p>错误信息表明测试确实如期望 panic 了,不过 panic 信息<code>did not include expected string 'Guess value must be less than or equal to 100'</code>。可以看到我们的到的 panic 信息,在这个例子中是<code>Guess value must be greater than or equal to 1, got 200.</code>。这样就可以开始寻找 bug 在哪了!</p>
<p>现在我们讲完了编写测试的方法,让我们看看运行测试时会发生什么并讨论可以用于<code>cargo test</code>的不同选项。</p>
</div>
<!-- Mobile navigation buttons -->
<a href="ch11-00-testing.html" class="mobile-nav-chapters previous">
<i class="fa fa-angle-left"></i>
</a>
<a href="ch11-02-running-tests.html" class="mobile-nav-chapters next">
<i class="fa fa-angle-right"></i>
</a>
</div>
<a href="ch11-00-testing.html" class="nav-chapters previous" title="You can navigate through the chapters using the arrow keys">
<i class="fa fa-angle-left"></i>
</a>
<a href="ch11-02-running-tests.html" class="nav-chapters next" title="You can navigate through the chapters using the arrow keys">
<i class="fa fa-angle-right"></i>
</a>
</div>
<!-- Local fallback for Font Awesome -->
<script>
if ($(".fa").css("font-family") !== "FontAwesome") {
$('<link rel="stylesheet" type="text/css" href="_FontAwesome/css/font-awesome.css">').prependTo('head');
}
</script>
<!-- Livereload script (if served using the cli tool) -->
<script src="highlight.js"></script>
<script src="book.js"></script>
</body>
</html>