相关疑难解决方法(0)

我怎样才能测试stdin和stdout?

我想编写一个提示函数,将传入的字符串发送到stdout,然后返回它从stdin读取的字符串.我怎么测试呢?

以下是该功能的示例:

fn prompt(question: String) -> String {
    let mut stdin = BufferedReader::new(stdin());
    print!("{}", question);
    match stdin.read_line() {
        Ok(line) => line,
        Err(e)   => panic!(e),
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的测试尝试

#[test]
fn try_to_test_stdout() {
    let writer: Vec<u8> = vec![];
    set_stdout(Box::new(writer));
    print!("testing");
// `writer` is now gone, can't check to see if "testing" was sent
}
Run Code Online (Sandbox Code Playgroud)

testing rust

7
推荐指数
1
解决办法
1786
查看次数

如何在测试中模拟外部依赖关系?

我已经在实现中使用外部箱子对汽车进行了建模和实现:

extern crate speed_control;

struct Car;

trait SpeedControl {
    fn increase(&self) -> Result<(), ()>;
    fn decrease(&self) -> Result<(), ()>;
}

impl SpeedControl for Car {
    fn increase(&self) -> Result<(), ()> {
        match speed_control::increase() {  // Here I use the dependency
          // ... 
        }
    }
    // ...
}
Run Code Online (Sandbox Code Playgroud)

我想测试上面的实现,但是在测试中,我不想speed_control::increase()表现出它在生产中的样子-我想模拟它。我该如何实现?

testing dependency-injection mocking rust

3
推荐指数
1
解决办法
409
查看次数

如何在 Rust 中模拟特定方法而不是所有方法?

我在找出目标结构的方法的单元测试时遇到了麻烦。

我有一个方法random_number根据结构的属性返回一个随机值,还有另一个方法plus_one可以获取第一个方法的结果并对其进行处理:

pub struct RngTest {
    pub attr: u64,
}

impl RngTest {
    pub fn random_number(&self) -> u64 {
        let random = 42; // lets pretend it is random
        return random * self.attr;
    }

    pub fn plus_one(&self) -> u64 {
        return self.random_number() + 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

对第一种方法进行单元测试,测试另一种方法的策略是什么?我想模拟self.random_number()单元测试的输出,以便在单元测试中plus_one()拥有健全的代码。有一篇很好的文章比较了不同的模拟库,并得出结论(很遗憾)它们中没有一个能真正从其他库中脱颖而出。

我在阅读这些库的说明时学到的唯一一件事是,我可以模拟方法的唯一方法是将它们移动到 trait。我在这些库中没有看到任何示例(我查看了其中的 4 或 5 个),它们测试了与此类似的案例。

在将这些方法移动到一个特征(即使它们是)之后,我如何模拟random_number对 的输出进行单元测试RngTest::plus_one?

pub trait SomeRng {
    fn random_number(&self) -> u64 {
        let random …
Run Code Online (Sandbox Code Playgroud)

testing unit-testing mocking rust

2
推荐指数
1
解决办法
1631
查看次数

使用“cfg!”宏在多个实现之间进行选择的正确方法是什么?

我在里面指定了一些功能Cargo.toml:

[features]
complex = []
simple = []
Run Code Online (Sandbox Code Playgroud)

当我构建项目时,我使用cargo build --features="complex"或simple.

在某些函数中,我想根据使用的功能返回一个值:

fn test() -> u32 {
    let x: u32 = 3;
    if cfg!(feature = "complex") {
        let y: u32 = 2;
        x + y
    }
    if cfg!(feature = "simple") {
        let y: u32 = 1;
        x + y
    }
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为它试图评估两个表达式。在我的情况下使用cfg!宏的正确方法是什么?

rust

1
推荐指数
1
解决办法
6228
查看次数

有没有办法检测是否从Rust的测试中调用代码?

我希望能够在我的代码本身内检查它是否在测试中运行.这样做是理想的,例如,与测试数据库,Web服务等接口.简单bool就足够了.

Rust有一个现有的API吗?

testing rust

0
推荐指数
1
解决办法
177
查看次数