Cargo Test Expected Macro Use


I'm working on a project involving integration tests in a separate directory from the production code, but all the code is in the same overall package. I'm running into an issue with cargo test and am curious if its expected output or not.

Here's an outline of what I'm trying to do:

My file structure is:

| - src
    | - methods
        | -
        | -
    | -
    | -
| - test
    | -
| - Cargo.toml

In I'm attempting to call a function in and the function has a cfg! macro in order to determine which output to print (either test or prod):
Code in

fn method_test() -> i32 {
    if cfg!(test) {
    } else {

Code in

mod test_try {
	use example::methods::method;

	fn try_main() {
		assert_eq!(method::method_test(), 0); // this test fails every time

When I run cargo run the code prints prod. When I run cargo test, main_test calls the function and it prints prod. Is this expected because of the different directories being compiled separately at compile time or is there something I'm doing wrong? Thanks for any feedback you can provide.

When you run cargo test, the following things are built:

  • The library example. (
  • A test harness for unit tests in the library. ( with --cfg test)
  • The binary example. (
  • A test harness for unit tests in the binary. ( with --cfg test)
  • A test harness for integration tests in (with --cfg test)

and then it runs all three test harnesses. All three of the last items (the things that aren't built from link to the library that was built without --cfg test. After all, the purpose of --cfg test is to enable and disable the generation of unit tests. The unit tests from were already compiled into a binary; there's no reason why of these downstream build artefacts should need them.

I would advise against using cfg(test) for any other purpose. If you want to alter the behavior of something in a test, I would suggest adding a feature:

something = []

name = "main_test"
path = "test/"
required-features = ["something"]

Hi ExpHP

Thanks so much for taking the time to explain all of that! Didn't know a whole lot about features as a cargo option, but feel that it makes a lot of sense in the case that I'm using it.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.