Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 219
petrbel Avatar asked Aug 01 '15 07:08

petrbel


People also ask

Where do I put the test files?

The convention for naming test files in Go is to end the file name with the _test.go suffix and place the file in the same directory as the code it tests. In the example above, the Multiply function is in integers.go , so its tests are placed in integers_test.go .

What is a test directory?

The Laboratory Test Directory is a complete, up-to-date test menu, with relevant test information, specimen collection requirements, storage, preservation, and transport guidelines.


2 Answers

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); }
like image 116
DK. Avatar answered Sep 28 '22 00:09

DK.


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

like image 30
Zarathustra30 Avatar answered Sep 28 '22 00:09

Zarathustra30