DEV Community

Willian Ferreira Moya
Willian Ferreira Moya

Posted on • Originally published at springmasteryhub.com

Structural-Based Testing: A Simple Guide

When writing tests for your code, it's easy to miss some parts, which can lead to bugs. How can you ensure you've tested everything properly?

Use structural-based testing!

What is Structural-based testing?

This technique is about considering your code when writing your tests.

It's a complementary technique and should be used as a support of other testing techniques.

The idea here is that you already have a test suite and you want to check if all branches and partitions of your code were already tested.

This can be achieved by looking at the line coverage report.

It will spot places that might be missing some test scenarios.

But do not use this to write tests right away. Use it to understand what’s going on first.

As I said it is a complementary technique that should be used to help you fill the gaps that your tests can be missing.

Use as a part of the process.

So what process is this?

  1. Specification-based testing: this will help you to create scenarios that match the specification expectations.
  2. Use coverage as a guide, not a goal: Run your coverage tool to see if some branches or partitions are missing.
  3. Understand the results: question yourself to get clarification, this will be a filter to write the missing tests later. Example:
    • Why this part was not covered by the test suite?
    • How this partition can be exercised?
    • Could this be missing from the specification?
    • Or just was an update?
    • Did someone just forget to write a test considering this branch?
    • Is the developer checking something that does not make sense at this moment?
  4. Create test scenarios: Write tests for what makes sense to fill the gaps of what went missing. For what it doesn't maybe you should refactor.

Additional tips:

Write meaningful assertions: it’s tempting to write tests that just pass through the code without testing anything, this will help you avoid this mistake. Some tests can fool the coverage metric, so make sure that are testing something.

Run mutation tests: by writing tests and looking at the code is easy to fool yourself and think that everything is ok because it’s covering all parts of your code. Mutation tests will put that into proof and help you to see what tests need some rework to improve their strength to catch bugs.

So next time you are going to create tests by looking at your code, following this process, will help you a lot!

For more tips, follow me on social media!

Willian Moya (@WillianFMoya) / X (twitter.com)

Willian Ferreira Moya | LinkedIn

Also follow me here on dev.to!

Top comments (0)