1

I have a binary project and I want to test it. I normally run my project like this:

cargo run -- -b localhost:8399

How can I do the same with cargo test?

use std::sync::Once;

static INIT: Once = Once::new();

pub fn init() {
    INIT.call_once(|| {
        // initialization code here
        let args: Vec<String> = std::env::args().collect();

        print!("got this as cmd args:-");

        for i in &args {
            print!(" {}", i);
        }
        println!("");

        //do something cool like
        // let _server = Command::new("cargo").args(args).spawn();
    });
}

#[test]
fn working() {
    init();
    println!("working!!!!!!!!");
}

#[test]
fn working2() {
    init();
    println!("working2222222222!!!!!!!!");
}

when I execute the above code, I get this:

❯ cargo test -- --nocapture --arg1 blabla --cool value --watch anime --everyday true
    Finished test [unoptimized + debuginfo] target(s) in 0.07s
     Running target/debug/deps/examer-2c07d411874ae585
error: Unrecognized option: 'arg1'
error: test failed, to rerun pass '--bin examer'

I expect it to output something like this:

got this as cmd args:- --arg1 blabla --cool value --watch anime --everyday true
working!!!!!!!!
working2222222222!!!!!!!!
test working ... ok
test working2 ... ok
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
너를 속였다
  • 899
  • 11
  • 26
  • This sounds like a bad idea in general, IMO. – Shepmaster Jul 27 '20 at 18:22
  • @Shepmaster My app is WebSocket server. The idea is that clients sends WebScoket Messages to it and it responds accordingly. So i was gonna write test functions which will send messages and check if server send correct message or not. for that, I need to start server with command line arguments so that it will run on some port other than default one and I will also be able to test my server with different flags. – 너를 속였다 Jul 27 '20 at 18:43
  • 1
    *write test functions* — this makes sense. *I need to start server with command line arguments* — this does not. Move the server code to `lib.rs`, call that from your tests and from the `main.rs`. Being required to pass command line arguments to run your tests will get tedious very quickly. See also [How to move tests into a separate file for binaries in Rust's Cargo?](https://stackoverflow.com/q/38995892/155423) – Shepmaster Jul 27 '20 at 18:46
  • Since you've been warned it's a bad idea, have you tried `cargo test -- -b localhost:8399`? – MeetTitan Jul 27 '20 at 21:31
  • @MeetTitan it does not work. I get Unrecognized option error. I'm currently using approach suggested by sir Shepmaster by hardcoding variables – 너를 속였다 Jul 28 '20 at 06:19
  • `cargo test` does not provide any way of passing command-line arguments to the binary, everything after `--` is limited to the [test option](https://doc.rust-lang.org/cargo/commands/cargo-test.html#test-options). – Ham Jul 23 '23 at 14:11

0 Answers0