Rabi Siddique
400 words
2 minutes
Testing

What is Unit Testing?#

Unit testing is the process of checking small parts of our code to ensure they work correctly on their own. A unit test typically includes three steps:

  • Arrange: Set up the code you want to test.
  • Act: Run the code using a specific action, like calling a method or function with inputs.
  • Assert: Check the results. If the outcome is what you expected, the test passes. If not, it fails.

These three steps are also known as the Arrange, Act, and Assert (AAA) pattern.

Good Link: Understanding Unit Testing

Why Unit Testing?#

Imagine you’ve added a new feature to your software. You might test your code manually and think it’s ready. But what if you make changes later? Testing everything manually again can be tedious.

That’s where unit tests help. You write tests once and run them anytime you change your code, with just a click. This catches problems early. By integrating these tests into your build process, you ensure small but important changes don’t introduce new bugs. It’s a great way to keep your code clean without the repetitive work of manual testing.

Good Read: More on Unit Testing

Unit Testing vs Integration Testing#

If your test involves operations like writing to a file, connecting to a database, or communicating over the network, it’s probably an integration test, not a unit test. Unit tests focus on small, independent sections of your code. Integration tests check how different parts of your system work together, especially when they interact with external resources like databases or networks.

Test Doubles#

”Test double” is a general term for any fake object used in testing. This includes dummies, fakes, stubs, and mocks.

Mocking#

When a part of your code relies on other objects, mocking is used to create simulations of those objects. This lets you isolate and test just the part of the code you’re interested in. Mocks mimic the behavior of real objects, which is useful when it’s impractical to use the real ones in your tests.

Good Link: What is Mocking?

Stubbing#

Stubs are simple fakes that replace real components your code depends on, like methods or functions. They provide pre-set responses when called during testing. Stubs don’t contain complex logic; they just return specific values or behave in a predictable way. For example, if your code calls a database service, you might use a stub to mimic the database service by returning fixed data instead of actually connecting to a real database.

Good Link: Understanding Stubs and Mocks

Testing
https://rabisiddique.com/posts/testing/
Author
Rabi Siddique
Published at
2023-11-19