DEV Community

Cover image for Why Testing Your Code Is Important
Simon Egersand 🎈
Simon Egersand 🎈

Posted on • Updated on • Originally published at prplcode.dev

Why Testing Your Code Is Important

Testing your code is an important part of the software development process. It's how you confirm that your code behaves as you want it to. It also allows you to find and fix bugs early on before they have a chance to cause problems in production.

In this article, we'll go over why testing your code is important. There are many different ways of testing your code, and we'll cover the most important way -- unit testing.

Always Test Your Code

Before we talk about the why's, let's talk about the what. What is code testing? It's making sure your code works the way you want it to work. Easy as that.

Now, why should you bother testing your code? Imagine you have a program with a single module. It's responsible for one thing and one thing only. Testing it might seem like overkill (but I recommend always testing your code). Now imagine your program has five modules that all do different things. Additionally, the modules communicate with each other. Your program now has many possible states and testing all states manually will take up a lot of your precious time.

Instead, you should write tests to confirm the behavior! By testing your code, you also protect yourself against breaking features when you add new code. You want to write quality code, right? That's not possible without testing it.

Unit Testing Your Code

There are various types of tests that you can run on your code, but unit tests are the most important. They allow you to test individual units of code in isolation.

Let's look at this JavaScript function.

const incrementByOne = input => {
  if (input < 0) {
    return 0;
  }

  return input + 1;
};
Enter fullscreen mode Exit fullscreen mode

Now let's write some tests. I like to start by testing the "happy path".

test('should increment by 1', () => {

  const input = 9;

  const actual = incrementByOne(input);
  const expected = 10;

  expect(actual).toBe(expected);
});
Enter fullscreen mode Exit fullscreen mode

And then for the fun part; the edge cases!

test('should return 0 when negative input', () => {

  const input = -1;

  const actual = incrementByOne(input);
  const expected = 0;

  expect(actual).toBe(expected);
});
Enter fullscreen mode Exit fullscreen mode

We've now tested everything, and have 100% test coverage. And we're happy, or are we?

I chose JavaScript because it's dynamically typed, and we're allowed to pass any type into our function (psst! This is a good reason to instead use TypeScript).

What happens if we pass a string?

test('should increment by 1', () => {

  const input = 'my-string';

  const actual = incrementByOne(input);
  const expected = ???;

  expect(actual).toBe(expected);
});
Enter fullscreen mode Exit fullscreen mode

The function will return my-string1 because the + operator works between types in JavaScript. This is not what we want, so let's fix it.

Let's update the function to handle this case.

const incrementByOne = input => {
  if (typeof input !== 'number') {
    throw new TypeError('Only number type allowed');
  }

  if (input < 0) {
    return 0;
  }

  return input + 1;
};
Enter fullscreen mode Exit fullscreen mode

And now let's add another test to our test suite.

test('should throw when non-number input', () => {

  const input = 'my-string';

  const expected = new TypeError('Only number type allowed');
  expect(() => incrementbyOne(input)).toThrowError(expected);
});
Enter fullscreen mode Exit fullscreen mode

This was a simple example. Websites and programs are never trivial though, and I hope you can see the value of testing your code now. Testing your code is a crucial part of delivering high-quality software. And it should be a fundamental part of your software development process!

Unit testing is not a silver bullet, and it is not a substitute for other forms of testing, such as system testing and user acceptance testing. But, unit testing is an important part of the software testing process and should not be ignored.

Conclusion

When it comes to code, testing is key to avoiding bugs and ensuring that your code runs as expected. By taking the time to test your code, you can avoid costly mistakes and ensure that your code is ready for prime time.

Enjoyed this post? Then check out Stop using meaningless test values!


Connect with me on Twitter, LinkedIn and Github

Originally published at prplcode.dev

Discussion (10)

Collapse
jwp profile image
John Peters • Edited on

I had taken a contract to modernize a large retail app. It was a monolithic mess, poorly documented, and little to no tests.

The first thing found was I inadvertently introduced a number of bugs. Missed all the deadlines and fell out of favor with the product owners.

So I began focusing on writing tests only. After 2 sprints I had gained huge internals knowledge from the tests and was able to deliver top quality work. I left Still not in good favor of product owner but couldn't care less because the ultimate refactoring and new functionality left them with a superior product.

The real issue was in how they allowed this to happen before I was hired, but no one wanted to acknowledge that part.

Collapse
simeg profile image
Simon Egersand 🎈 Author

This is a very good point I didn't mention in my post. Writing tests is a good way to learn a new codebase, especially if it's lacking tests. There's really no downsides to writing tests if you do it the right way.

Collapse
andrewbaisden profile image
Andrew Baisden

So true its a habit all developers should get used to.

Collapse
simeg profile image
Simon Egersand 🎈 Author

Yeah, definitely agree. It should be part of the process of writing code!

Collapse
heyodai profile image
Odai Athamneh

Great article! The Agile Testing Quadrant is good reference material for testing.

Collapse
tracygjg profile image
TGJ Gilmore

In my opinion, writing a unit of code without a unit test to prove it works as the developer intended is half-written. Any software engineer that only writes code and no unit test is failing to do the job for which they are being paid.

Collapse
jonrandy profile image
Jon Randy • Edited on

You want to write quality code, right? That's not possible without testing it.

This simply isn't true. I've been a professional developer for 26 years and have used automated testing extremely rarely

Collapse
jeremyf profile image
Jeremy Friesen

Could you expand on what your approach is? Super curious because my first 9 years coding was no automated testing (and things worked) but now I don't quite know how I'd do otherwise.

Collapse
simeg profile image
Simon Egersand 🎈 Author

I find this very interesting. Did you ever work on a big project? I don't understand how you can maintain the quality without automated testing on a big project. Very curious, please share :)

Collapse
jonrandy profile image
Jon Randy • Edited on

I've worked on plenty of big projects. It's my honest opinion that you do better work if you fully (or as close to fully as is possible) understand the code you are working with, and understand the implications of any changes you are making.

If you are writing new code, then this understanding is obviously almost instant as you will (presumably) know what your code is doing. If you are working with old or unfamiliar code, then I always find the best thing is to familiarise yourself with that code completely before working on it - noting the places where it is used etc. - so you'll know what you need to test when you make your changes.

I feel this approach results in having developers with a far greater understanding of project code than they would have by relying on tests (which may or may not be up to date, and are a level removed from real-world use - so knowledge gleaned from reading them is often incomplete or somewhat disembodied). Working without tests means your understanding of the code you are working with is always fresh and up to date, and you gradually acquire a deeper understanding of more and more parts of a large project. The more you understand in the code, the better you become at working with it.

For me, relying on automated tests takes away a lot of the opportunity to build a deep understanding of a project.

Yes, this method may be slower sometimes... but it has always worked very well for me.