How do I access exported functions inside a crate's “tests” directory?

南笙酒味 提交于 2021-02-07 04:18:47

问题


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

src/relations.rs:

#![crate_type = "lib"]

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

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;
                                                 ^~~~~~~~~

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;
                                                 ^~~~~~~~~~~~~~

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


回答1:


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.

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)

And src/lib.rs file contains this:

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

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();
}



回答2:


The solution was to specify a crate_id at the top of src/relations.rs:

#![crate_id = "relations"]
#![crate_type = "lib"]

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

This seems to declare that all the contained code is part of a "relations" module, though I'm still not sure how this is different to the earlier mod block.



来源:https://stackoverflow.com/questions/26390773/how-do-i-access-exported-functions-inside-a-crates-tests-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!