DEV Community

Kishan B
Kishan B

Posted on • Edited on • Originally published at kishaningithub.github.io

1

Used TDD approach for a Hello World rust cli app

For the first time ever in my life i wrote hello world application using TDD (Test driven development). Don't get me wrong here, i have practiced TDD before for larger applications but never have i done it for an hello world app.

Problem

Write an CLI application that prints out "Hello TDD world!" in STDOUT.

How did i do it?

  • I created a project using cargo new hello-world-tdd
  • I added a dependency assert_cmd which lets us test out outputs of any binary program
  • Created a file tests/cli.rs and I wrote the following test
use assert_cmd::Command;

#[test]
fn test_cli_app_should_print_hello_tdd_world() {
    let mut cmd = Command::cargo_bin("hello-world-tdd").unwrap();
    cmd.assert().success().stdout("Hello TDD world!\n");
}
Enter fullscreen mode Exit fullscreen mode
  • Run the test using command cargo test
  • The above test will fail saying the following, this happens because the cargo new had generated a src/main.rs file which printed out "Hello world!"
running 1 test
test test_cli_app_should_print_hello_tdd_world ... FAILED

failures:

---- test_cli_app_should_print_hello_tdd_world stdout ----
thread 'test_cli_app_should_print_hello_tdd_world' panicked at 'Unexpected stdout, failed diff original var
├── original: Hello TDD world!
├── diff:
│   ---   orig
│   +++   var
│   @@ -1 +1 @@
│   -Hello TDD world!
│   +Hello world!
└── var as str: Hello world!
Enter fullscreen mode Exit fullscreen mode
  • Now that we have a failing test(RED), the next job is to make it green by modifying the contents of the println statement.
  • Run cargo test again, The test now passes (Green)

The code for this is available at https://github.com/kishaningithub/hello-world-tdd

Links

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay