Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you write your unit tests before or after coding a piece of functionality? [closed]

I was wondering when most people wrote their unit tests, if at all. I usually write tests after writing my initial code to make sure it works like its supposed to. I then fix what is broken.

I have been pretty successful with this method but have been wondering if maybe switching to writing the test first would be advantageous?

like image 801
faceless1_14 Avatar asked Dec 29 '08 16:12

faceless1_14


People also ask

Should you write unit tests before code?

It often makes sense to write the test first and then write as much code as needed to allow the test to pass. Doing this moves towards a practice known as Test-Driven Development (TDD). Bluefruit uses a lot of TDD because it helps us to build the right product without waste and redundancies.

Should I write unit test before or after?

For Test-Driven Development (TDD), you write unit tests before writing any implementation. This makes your implementation details in your code shorter and easier to understand. In this instance, the best time to write unit tests is immediately. For others, most developers write unit tests after the code's been written.

Can you put unit tests before the function definition?

Arguably you must write all of the unit tests for a feature first in order to fully define the interface of the feature. In practice many features only have 1 test (at least to start)...

When should the unit testing be performed?

Unit Testing of the software product is carried out during the development of an application. An individual component may be either an individual function or a procedure. Unit Testing is typically performed by the developer. In SDLC or V Model, Unit testing is the first level of testing done before integration testing.


1 Answers

whenever possible i try to follow a pure TDD approach:

  1. write the unit tests for the feature being developed; this forces me to decide on the public interface(s)
  2. code the feature ASAP (as simple as possible, but not simpler)
  3. correct/refactor/retest
  4. additional tests if required for better coverage, exceptional paths, etc. [rare but worth consideration]
  5. repeat with next feature

it is easy to get excited and start coding the feature first, but this often means that you will not think through all of the public interfaces in advance.

EDIT: note that if you write the code first, it is easy to unintentionally write the test to conform to the code, instead of the other way 'round!

like image 148
Steven A. Lowe Avatar answered Oct 04 '22 15:10

Steven A. Lowe