Cloud Studio代码运行 #[cfg(test)]mod tests{#[test]fntest_addition(){assert_eq!(2+2,4);}#[test]fntest_subtraction(){assert_eq!(5-2,3);}} 在上述示例中,我们使用#[cfg(test)]属性标记了测试模块。在该模块内部,我们定义了两个测试函数test_addition和test_subtraction,并使用#[test]属性标记它们。
在测试函数前面一行应有声明#[test],如下: //File name: src/lib.rs#[cfg(test)] mod tests { #[test] fn it_works(){ assert_eq!(2+2,4); } } $ cargo test Compiling adder v0.1.0(file:///projects/adder)Finished test [unoptimized + debuginfo] target(s)in0.72s Running target/debug/de...
#[cfg(test)]mod tests {#[test]fn it_works(){ assert_eq!(2+2,4);} } 1. 2. 3. 4. 5. 6. 7. 测试函数需要使用#[test]属性进行标记。在测试函数中,使用assert_eq!宏来进行结果断言,从而验证被测试的代码是否符合预期。 使用cargo test运行测试 要运行所有测试,只需在项目根目录下运行以下命令...
#[cfg(test)] mod tests { use std::collections::hash_map::RandomState; use super::LruCache; #[test] fn test_insert() { let mut m = LruCache::new(2); assert_eq!(m.len(), 0); m.insert(1, 2); assert_eq!(m.len(), 1); m.insert(2, 4); assert_eq!(m.len(), 2); m...
#[cfg(test)] mod tests { use super::*; #[test] fn test_declare_int() { let array = ivec![1,2,3,4]; assert_eq!(array.len(), 4); assert_eq!(array[0], 1); assert_eq!(array[1], 2); assert_eq!(array[2], 3); ...
测试模块的#[cfg(test)]注解告诉Rust只在执行cargo test时才编译和运行测试代码,而在运行cargo build时不这么做。这在只希望构建库的时候可以节省编译时间,并且因为它没有包含测试,所以能减少编译产生的文件的大小。与之对应的集成测试因为位于另一个文件夹,所以它们并不需要#[cfg(test)]注解来指定他们不应被包含...
#[cfg(test)] mod tests { #[test] #[should_panic] fn test_panic { assert!(false, "This test should panic"); } } 通过使用#[should_panic]属性,你可以指定一个测试函数应当触发panic。 自定义panic信息 对于需要具体panic信息的情况,我们可以使用expected参数,如下所示: ...
标准一点可以写一个 #[cfg(test)] 模块 #[cfg(test)]modtests{#[test]fntest_eq(){assert_eq!(2+2,4)}#[test]fntest_eq2(){assert_eq!(2+2,5)}} image.png 测试失败可以使用 panic 函数,就表示失败。 每个测试运行在一个新线程里。
在Rust中,可以使用#[cfg(test)]属性来测试宏。这个属性用于标记测试代码,只有在运行测试时才会编译和执行。下面是一个示例: 代码语言:txt 复制 #[cfg(test)] mod tests { macro_rules! my_macro { () => { println!("Hello, macro!"); };
#[cfg(test)] mod tests { #[test] #[should_panic] fn test_panic { assert!(false, "This test should panic"); } } 通过使用#[should_panic]属性,你可以指定一个测试函数应当触发panic。 自定义panic信息 对于需要具体panic信息的情况,我们可以使用expected参数,如下所示: ...