petrbel
petrbel

Reputation: 2528

How to make a test dir?

I'd like to set up a basic hello world project. The unit tests should be in the test/ directory as described in the book. My code so far is as follows.

src/main.rs

pub mod player;

fn main() {
    println!("Hello, world!");
}

src/player.rs

pub fn rep(arg: i32) -> i32 {
    arg
}

tests/player.rs

extern crate player;

#[test]
fn it_works() {
    assert_eq!(4, player::rep(2+2));
}

Cargo.toml

[package]
name = "myapp"
version = "0.1.0"
authors = ["My Name <[email protected]>"]

I believe the code is very similar to the book. However, cargo test fails:

tests/player.rs:1:1: 1:21 error: can't find crate for `player`
tests/player.rs:1 extern crate player;
              ^~~~~~~~~~~~~~~~~~~~
error: aborting due to previous error

What is the problem? I'm completely lost.

Upvotes: 7

Views: 1441

Answers (2)

DK.
DK.

Reputation: 58975

There are two problems. First of all, you're building an executable, not a library, so you can't link against the result to test it. Secondly, you appear to be confused as to the difference between modules and crates. You might want to read the Crates and Modules chapter of the Rust book.

If you want types and methods from your crate to be externally accessible, you need to compile your code into a library. Often, executables in Rust will just be thin wrappers around a library of the same name. So, you might have:

// src/main.rs
extern crate player;

fn main() {
    println!("rep(42): {:?}", player::rep(42));
}

// src/lib.rs
pub fn rep(arg: i32) -> i32 { arg }

This would allow you to test player::rep.

The other thing you can do is just write the test next to the code it's testing.

// src/lib.rs
pub fn rep(arg: i32) -> i32 { arg }

#[test]
fn test_rep() { assert_eq!(rep(4), 4); }

Upvotes: 6

Zarathustra30
Zarathustra30

Reputation: 56

You are compiling a binary instead of a library (crate). Try renaming "main.rs" to "lib.rs".

Upvotes: 2

Related Questions