Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

"Unit" is not well-defined. However, it usually means a function/method. Being a unit test also implies some explicit setup for when that function is used.

The easiest examples of unit tests are math functions, since they're so well-behaved.

Here is a square root function in Javascript:

    function sqrt(n) {
      guess = n/2;
      while(Math.abs(guess*guess - n) < 0.00001) {
        guess = (guess + n/guess)/2;
      }
      return n;
    }

    assert_equals(4.0, sqrt(16));
There is nothing to set up because this code doesn't depend on a database, or an HTML input field, or the phase of the moon.

The call to assert_equals there is a unit test. (Also, keep in mind that assert_equals is a glorified if statement)

"well, what isn't a unit test??"

Since we can call anything we want a unit, the answer is "whenever we say we aren't doing a unit test". But a more practical answer is: whenever you're testing the interaction between two or more units (where a unit is a function/method).

If you're making a video game, you might have enemies who can jump, and guns that can fire. It would be a unit test to check if enemies jump correctly, and it would be a unit test to see if guns fire correctly. It wouldn't be a unit test to see if guns fire correctly from a jumping enemy, since this is the combination of two pieces.

Another way to (sort of) define a unit test is to say "how does this behave assuming that the rest of the system is correct"? That is, we aim to check the behavior of our code in isolation from the rest of the system.

This is important when something is wrong, because if we know what is behaving correctly, we don't have to waste time checking if it's the cause.



Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: