Creating tests in separate directory

So I have a module I am creating called: "etimer_unix"
I created it with 'cargo new --lib etimer_unix'
The Cargo.toml file has an entry like this:

[package]
name="etimer_unix"


I have src directory where I have my implementation
I have a file called src/lib.rs, and it contains 1 function declared as follows:

#[allow(non_snake_case)]
pub extern "C" fn ETIMER_getNow() -> u32 {
  // implementation details omitted
  return 42;
}

I have a test directory where I have my separate test files.
I have a file named: tests/test_get_now.rs which has this:

use std::{thread,time};
use ETIMER_UNIX::*;  /* WHAT SHOULD THIS BE??? */

#[test]
fn test_getnow_msecs() // cspell: words getnow, mess
{
    let start = ETIMER_getNow(); // cspell: words ETIMER
    // and other things committed here
}

When I build the module using "cargo build" - it builds with no warnings
When I try to build for test, ie: 'cargo test' I get the error:

error[E0432]: unresolved import `ETIMER_UNIX'

I have tried the capitalization schemes none of these work.

I think the problem is in my 'test_get_now.rs' I need to import the DUT module but that's not working and I'm evidently doing it wrong.


The closest example I can find is this - but this is as if the test is using some other module, not the current active module

When you create a test file in tests/ (rather than in src/ as a module of the library crate), the test file is compiled as a separate crate. (If you are familiar with C, then: a crate is a translation unit.) This means that the test must use your library crate in the same way any other dependent on your library crate would.

By default, the name of a library crate is the same as the name of the package.[1] So, the name of your library crate is etimer_unix. Therefore, the correct import is:

use etimer_unix::*;

If you try this and still get an error, please show us:

  • The full output you get from cargo test. Do not leave anything out just because it looks irrelevant. When troubleshooting problems of this kind, every detail of the output from the first to the last line may be helpful. The compiler is trying to help you, not spam you.
  • The full contents of your Cargo.toml file.

By the way, I recommend not using glob imports (::*) for situations like this. They make it hard for readers to understand which names in the file come from that library, and which come from elsewhere. That is, however, a matter of style, not part of the problem you are having.


  1. Unless the package name contains β€œ-”, in which case it is replaced with β€œ_”. β†©οΈŽ

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.