-1

This may not be the right place to ask this. However, I was just hired a couple of months ago at my first programming job as a student developer for my university, and I have had to write a couple of unit tests already. Before I was hired, I had the opportunity to talk to another developer who made the case unit tests were not necessary. He made the case: if you throw data at a method should know what comes out without writing a test, which I think makes sense.

For example (Java):

public int Add(int num1, int num2) {
   return(num1 + num2);
}
//if I call Add(2,2) I know I should get 4, 
//if I call Add(5,6) I know I should get 11,
//etc...

I tried asking my co-worker about this and his response was more or less along the lines of, everyone else does it so we have to.

So, I guess my question is: Why are unit tests necessary if you can just test your code by calling it repeatedly with dummy data rather than testing it once with a unit test?

Michael Dorgan
  • 12,453
  • 3
  • 31
  • 61
Seth Wheeler
  • 353
  • 1
  • 2
  • 16
  • There will be many possible paths to answer this, but I think the most important one is: writing unit tests for your code will make you understand the code you are writing much better and thus discover potential weaknesses and potentials for improvement. – m90 Mar 01 '19 at 18:59
  • That argument, at least as presented here, makes no sense as an objection to unit tests. If you know what you expect out given those inputs, why *not* express that expectation in a way that can automatically be verified? *"you can just test your code by calling it repeatedly with dummy data"* - that sounds quite a lot like unit testing... – jonrsharpe Mar 01 '19 at 19:01
  • 1
    Major benefits of UT IMO: 1 check the code does (only) what it's supposed to do now 2 check the code still does what it's supposed to do in the future 3 put yourself in the feet of a consumer of your code and detect design issues 4 provide some kind of additional documentation for those wanting to understand the code. To be honest if a dev tells me UTs are not necessary during an interview: game over (never happened). – vc 74 Mar 01 '19 at 19:12
  • Unit testing is automated sanity testing. – Compass Mar 01 '19 at 19:15

1 Answers1

1

A unit test is a specific written test in an easy to manage and run framework that works by calling your code with "dummy data". Of course, a good test will also hit all sorts of edge cases as well.

Just for fun, let's take your code:

What happens if I pass it INT_MAX (not sure of Java equivalent of this, but perhaps Integer.MAX_VALUE) as num1 and say 10 as num2 into your code. Will it return INT_MAX + 10 or something else? If it does so, is that an error condition or expected? A unit test can formalize these questions as well.

Michael Dorgan
  • 12,453
  • 3
  • 31
  • 61