如何访问板条箱的“测试"中的导出函数?目录? [英] How do I access exported functions inside a crate's "tests" directory?

查看:39
本文介绍了如何访问板条箱的“测试"中的导出函数?目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在创建的tests"目录中访问我的库导出函数?

How do I access my libraries exported functions inside the create's "tests" directory?

src/relations.rs:

src/relations.rs:

#![crate_type = "lib"]

mod relations {
    pub fn foo() {
        println!("foo");
    }
}

tests/test.rs:

tests/test.rs:

use relations::foo;

#[test]
fn first() {
    foo();
}

$ cargo test
   Compiling relations v0.0.1 (file:///home/chris/github/relations)
/home/chris/github/relations/tests/test.rs:1:5: 1:14 error: unresolved import `relations::foo`. Maybe a missing `extern crate relations`?
/home/chris/github/relations/tests/test.rs:1 use relations::foo;
                                                 ^~~~~~~~~

如果我添加建议的extern crate关系,错误是:

If I add the suggested extern crate relations, the error is:

/home/chris/github/relations/tests/test.rs:2:5: 2:19 error: unresolved import `relations::foo`. There is no `foo` in `relations`
/home/chris/github/relations/tests/test.rs:2 use relations::foo;
                                                 ^~~~~~~~~~~~~~

我想在这个单独的 tests/test.rs 文件中测试我的 relations.如何解决这些使用问题?

I want to test my relations in this separate tests/test.rs file. How can I solve these use issues?

推荐答案

您的问题是,首先,mod 关系 不是公开的,因此在 crate 之外是不可见的,其次,您不要在测试中导入您的箱子.

Your problem is that, first, mod relations is not public so it is not visible outside of the crate, and second, you don't import your crate in tests.

如果您使用 Cargo 构建程序,那么 crate 名称将是您在 Cargo.toml 中定义的名称.例如,如果 Cargo.toml 看起来像这样:

If you build your program with Cargo, then the crate name will be the one you defined in Cargo.toml. For example, if Cargo.toml looks like this:

[package]
name = "whatever"
authors = ["Chris"]
version = "0.0.1"

[lib]
name = "relations"  # (1)

并且 src/lib.rs 文件包含这个:

And src/lib.rs file contains this:

pub mod relations {  // (2); note the pub modifier
    pub fn foo() {
        println!("foo");
    }
}

然后你可以在tests/test.rs中写这个:

Then you can write this in tests/test.rs:

extern crate relations;  // corresponds to (1)

use relations::relations;  // corresponds to (2)

#[test]
fn test() {
    relations::foo();
}

这篇关于如何访问板条箱的“测试"中的导出函数?目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆