Testing and Modules

sarahhudaib

Sarah Hudaib

Posted on January 18, 2023

Testing and Modules

What are Unit tests and TDD?

Unit tests:

Unit tests are some pieces of code that exercise the input, the output, and the behavior of your code.

TDD tests:

Test-Driven Development is a strategy that entails first thinking about (and writing!) tests.

Baby Steps:

  1. what is the smaller test that we can do against a function?
  def test_should_return_female_when_the_name_is_from_female_gender():
    detector = GenderDetector()
    expected_gender = detector.run(Ana)
    assert expected_gender == female
Enter fullscreen mode Exit fullscreen mode
  1. There are some details to pay attention. The first one is the test name. The tests can be considered as your live documentation.

  2. The test file name should follow the same name as the module name.

  3. It’s ideal to separate the tests folder from the production code (the implementation)

  4. Another thing to care about is the structure. A convention widely used is the AAA: Arrange, Act and Assert.

  • Arrange: you need to organize the data needed to execute that piece of code (input)

  • Act: here you will execute the code being tested (exercise the behaviour)

  • Assert: after executing the code, you will check if the result (output) is the same as you were expecting

The Cycle:

The cycle is made by three steps:

  • 🆘 Write a unit test and make it fail (it needs to fail because the feature isn’t there, right? If this test passes, call the Ghostwriters, really)

  • ✅ Write the feature and make the test pass! (you can dance after that)

  • 🔵 Refactor the code — the first version doesn’t need to be the beautiful one (don’t be shy)

Takeaways

To remember:

  • The greatest advantage of TDD is to craft the software design first.

  • Your code will be more reliable: after a change, you can run your tests and be in peace.

  • The beginning may be hard — and that’s fine. You just need to practice!

💖 💪 🙅 🚩
sarahhudaib
Sarah Hudaib

Posted on January 18, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Testing and Modules
webdev Testing and Modules

January 18, 2023