Skip to content

How do you write testable code? #189

Open
@MartinMuzatko

Description

@MartinMuzatko

Not sure if that is out of the scope of this best practice guide. I, however, miss an integral part that explains how to write code that is easier to test in the first place.

That is only explained on the side in point 1.13 - other generic testing hygiene. This could be split into two or three points that specificially focus on the do's and don'ts to enable testing and how to structure such code.

This is my subjective view or recommendation I would put into the list:

Bad examples:

  • Using global state can make testing a nightmare, when two tests attempt to access the same state at the same time.
  • Mutability grants loopholes for impossible state

Good examples:

  • Extract pure data handling and decision making to their own side-effect free function to promote easier testing
  • Make options and behavior configurable (using dependency injection/rejection in function parameters/class constructor) to allow unit-testing.

In my experience, that goes hand in hand with benefits like more readable code, configurable behavior and options, focused functions. Some recommendation how to structure code or functions in a way that enables testing in the first place would be great.

What do you think?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions