rust - 在测试期间忽略部分功能
问题描述
我有一个调用函数的应用程序,该函数最后有一段需要一段时间才能运行的逻辑。我已经独立测试了这个逻辑,因为它是它自己的功能,但它目前使我的测试花费的时间比我希望的要长得多。
有没有一种方法可以让长时间运行的功能在正常使用期间运行,但在我测试hello_world
功能时不运行?
fn main() {
hello_world();
}
fn hello_world() {
println!("Hello, world!");
// Can I ignore this when testing?
long_running_function();
}
fn long_running_function() {
for i in 1..100000 {
println!("{}", i);
}
}
#[test]
fn hello_world_test() {
hello_world();
}
解决方案
您可以使用#[cfg(not(test))]
:
#[cfg(not(test))]
long_running_function();
或宏等价物:
if !cfg!(test) {
long_running_function();
}
单元测试中的一种常见方法是模拟外部函数,可以提供两个单独的实现,long_running_function
具体取决于它是为测试还是目标编译。
#[cfg(not(test))]
fn long_running_function() {
for i in 1..100000 {
println!("{}", i);
}
}
#[cfg(test)]
fn long_running_function() {
// not so long code
}
否则,您始终可以将布尔值传递给hello_world()
并根据该布尔值创建条件。
推荐阅读
- sql - 使用 WITH 子句的 SQL INSERT/SELECT
- java - Jackson Deserializer 在失败时默认为 null
- ldap - 将主机 ldap 服务器连接到本地 VM
- reference - (Anylogic)如何从另一个代理引用 Main
- python - Discord bot 在语音聊天中断开随机用户的连接
- mapping - 从括号切换到 Visual Studio Code
- c# - OnTriggerEnter2D 仅在 Unity 中触发它的对象上更改 int
- python - Selenium 页面源
- c++ - extern "C" 是将 C 代码转换为 C++ 代码,还是只允许编译器将 C 代码编译为 C++ 代码?
- r - geom_smooth 没有回归线