[英]How to write regression tests for a Rust binary crate?
There's a lot of similar posts in the past 1 2 3 4 but they all seem outdated or irrelevant.过去1 2 3 4有很多类似的帖子,但它们似乎都已过时或无关紧要。
My question is: how do you write regression tests for Rust binaries?我的问题是:你如何为 Rust 二进制文件编写回归测试?
I could set them up as "unit tests" in my src/main.rs
file, but that's annoying.我可以在我的src/main.rs
文件中将它们设置为“单元测试”,但这很烦人。 Ideally, it would be set up as理想情况下,它将设置为
root
|---src
|---main.rs
|---foo.rs
|---bar.rs
|---tests
|---regress1.rs
|---regress2.rs
Two options:两种选择:
Split your code into a library and a binary: src/lib.rs
and src/main.rs
.将您的代码拆分为一个库和一个二进制文件: src/lib.rs
和src/main.rs
。 Then you can write tests/
tests that can load the library part.然后您可以编写可以加载库部分的tests/
测试。
This option is best if you specifically want to take advantage of the fact that tests/
tests ("integration tests") are individual binaries on their own (eg if the code you want to test uses global variables or system calls that affect global state).如果您特别想利用tests/
测试(“集成测试”)本身就是单独的二进制文件这一事实(例如,如果您要测试的代码使用全局变量或影响全局状态的系统调用),则此选项是最佳选择.
You can write #[test]
tests in your binary's code without putting them directly in your src/main.rs
file.您可以在二进制代码中编写#[test]
测试,而无需将它们直接放在src/main.rs
文件中。 Just write mod tests;
只需编写mod tests;
or mod tests { mod regress1; }
或mod tests { mod regress1; }
mod tests { mod regress1; }
and put your tests in src/tests/regress1.rs
, and in that file write #[test]
functions as usual. mod tests { mod regress1; }
并将您的测试放在src/tests/regress1.rs
中,然后像往常一样在该文件中编写#[test]
函数。 (Or, if you really want them in a different directory, use the #[path]
attribute on mod
.) (或者,如果您真的希望它们位于不同的目录中,请在mod
上使用#[path]
属性。)
This option allows faster test execution, because the tests aren't separate binaries and will be run parallel in threads by the Rust test harness.此选项允许更快的测试执行,因为测试不是单独的二进制文件,并且将由 Rust 测试工具在线程中并行运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.