编写集成测试时如何从主 crate 访问函数? [英] How to access functions from the main crate when writing integration tests?

查看:45
本文介绍了编写集成测试时如何从主 crate 访问函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用这样的测试创建项目时:

When creating a project with a test like so:

cargo init --bin projectname
mkdir projectname/tests
echo "extern crate projectname;" > projectname/tests/test.rs
cd projectname/
cargo build

我在测试时收到此错误:

I get this error when testing:

cargo test
   Compiling projectname v0.1.0 (file:///home/username/Lab/projectname)
error[E0463]: can't find crate for `projectname`
 --> tests/test.rs:1:1
  |
1 | extern crate projectname;
  | ^^^^^^^^^^^^^^^^^^^^^^^^^ can't find crate

如何从 projectname/tests/test.rs 访问projectname/src/main.rs"中的函数?

How can I access the functions in ´projectname/src/main.rs´ from projectname/tests/test.rs?

推荐答案

如何从 projectname/tests/test.rs 访问projectname/src/main.rs"中的函数?

How can I access functions in ´projectname/src/main.rs´ from projectname/tests/test.rs?

你不能.

二进制文件不能用于外部 crate(就像你不能将 ELF 二进制文件用作共享对象/库一样)

A binary cannot be used a an external crate (the same way as you can't use a ELF binary as a shared object/library)

您只需要将初始化更改为

You just have to change your initialisation to

cargo init --lib projectname

或将您的 main.rs 重命名为 lib.rs

or rename your main.rs to lib.rs

如果你真的想坚持一个主要的,你可以看看 同时包含库和二进制文件的 Rust 包?.

If you really want to stick with a main, you may look at Rust package with both a library and a binary?.

这篇关于编写集成测试时如何从主 crate 访问函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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