我试图使用fmt::Display打印枚举(或结构)。虽然代码编译并获得了display方法,但它没有打印值。
pub enum TestEnum<'a> {
Foo(&'a str),
Bar(f32)
}
impl<'b> fmt::Display for TestEnum <'b> {
fn fmt(&self, f : &mut fmt::Formatter) -> fmt::Result {
println!("Got this far");
match self{
&TestEnum::Foo(x) => write!(f,"{}",x),
&TestEnum::Bar(x) => write!(f,"{}",x),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_print() {
let cell = TestEnum::Str("foo");
println!("Printing");
println!("{}",cell); // No output here
}
}我尝试使用{:}和{},但没有结果。
发布于 2015-06-12 12:52:11
这是因为锈蚀测试程序隐藏了成功测试的标准。您可以通过以下方式禁用此行为,即传递--nocapture选项来测试二进制文件或货物测试命令:
cargo test -- --nocapturePS:你的代码坏了/不完整。
发布于 2015-06-12 12:40:22
测试运行程序似乎转移了标准输出;您应该考虑使用assert!、assert_eq!或其他惊慌的方法来测试断言,而不是在测试中打印。
此外,由于名称不匹配,您的代码无法编译。我从main那里得到了预期的效果:
use std::fmt;
pub enum TestEnum<'a> {
Foo(&'a str),
Bar(f32)
}
impl<'b> fmt::Display for TestEnum <'b> {
fn fmt(&self, f : &mut fmt::Formatter) -> fmt::Result {
match self {
&TestEnum::Foo(x) => write!(f, "{}", x),
&TestEnum::Bar(x) => write!(f, "{}", x),
}
}
}
fn main() {
let cell = TestEnum::Foo("foo");
println!("Printing");
println!("{}", cell);
}发布于 2015-06-12 12:44:39
当测试成功时,测试输出被重定向到缓冲区,以避免测试“失败”或“确定”消息损坏。
如果您只想在开发测试时测试一些东西,那么始终可以在测试结束时添加一个panic!(),以确保它始终失败并输出所有日志记录。或者,正如@AndreaP在他的答案中所指出的,您可以使用cargo test -- --nocapture来显示所有测试的标准输出。
通常,一个测试不应该写到stdout,而是写到一个缓冲区,并检查该缓冲区是否包含它应该包含的内容:
let cell = TestEnum::Foo("foo");
let mut buf = Vec::new();
let _ = write!(buf, "{}\n", cell);
assert_eq!(&buf, b"foo\n");如果你真的想输出什么,你需要直接写到stdout。
let _ = write!(io::stdout(), "{}\n", cell);但这将与测试的输出相结合:
test tests::blub ... foo
okPlayPen
https://stackoverflow.com/questions/30802714
复制相似问题