Originally posted on samueleresca.net
The advantages are:
- run tests in numerous browsers with a single effort;
- rerun tests at any later stage;
- schedule tests run;
A unit test is a piece of code that tests a piece of production code. A unit test sets application objects Â in a known state and then it runs the code to test, finally it compares the result to the expected outcome. Unit test are subject to isolation guidelines:
- no test should ever depend on antoher test;
- tests should be able to run simultaneously and in any order;
- to maintain islation, sometimesÂ is necessary to mock or stub test dependencies;
- a test should exercises only one unit, but it may do using one or more assertions;
Setup, or test fixture, is a piece of code that runs before the execution of an unit test. It sets the state of the application in a "known state".
Most software you develop is made up of a variety of classes and components, mock objects mimic the behavior of real components. "Mock" has become a generic term for the various types of mocks. Here's an article written by Martin Fowler that explain the difference between mock, stubs, fake, spy and dummy.
Testing your application takes time and the manual testing process is highly inefficient. There are a lot of benefits by using unit tests: regression testing, refactoring and cross-browser testing. Â
Test-driven development Â is a programming technique that moves unit tests to the front row. In test-driven development tests are written as specification before writing production code:Â we must describe the problem we are trying to solve.Â In other words, TDD requires us to think about the results before providing the solution.
- Write the unit test for the functionÂ you're going to implement, the unit test should be short and focus on a single behavior of a function. Â Tests describe the objectÂ youÂ are implementing, and it should not be necessary to change them unless the objectÂ itself changes;
- Watch the test fail without writing the passing codeÂ allows us to confirm our theories about the current state of our code;
- Make the test pass by providing the simplest solution that could possibly work;
- Refactor to remove duplication. At the end, we need toÂ review the work Â and make necessary adjustments to remove duplication and improve design. There is only one rule to obey during this step: tests should stay green;
The strongest benefits of TDD is that it produces code that works and forces us to think about our code before writing it. The TDD process describesÂ specialized components in isolation Â and that honors the single responsibility principle.