2. @nikhilwanpal | NikhilWanpal
What is Unit Testing
● Asserting the code does what it says it does
● Specification of system’s behaviour
● A way of verifying the system’s behaviour
● A way to avoid and reduce regression
● A mesh or net to help refactor, without altering the behaviour
● A way to achieve faster, reliable, maintainable speed of development
3. @nikhilwanpal | NikhilWanpal
How to test
● Fast, Independent, Repeatable, Self-validating, Timely
● In an isolated, contained environment
● Specification of system’s behaviour
○ Given some conditions, given a state of a system (unit)
○ When a certain action is taken
○ Expected result should be seen
● AAA:
○ Arrange
○ Act
○ Assert
● Yes the scenarios (Arrange / Given) might appear hardcoded.
4. @nikhilwanpal | NikhilWanpal
TDD
● Tests are tests for code
● Code is test for test
● Laws of TDD:
○ First Law: You may not write production code until you have written a failing unit test.
○ Second Law: You may not write more of a unit test than is sufficient to fail, and not compiling
is failing.
○ Third Law: You may not write more production code than is sufficient to pass the currently
failing test
5. @nikhilwanpal | NikhilWanpal
What to test
● Test for all initial and end states of the system
● Test for all types of events/input to the system
● Test the happy path
● Test the exception paths
● Test the edge conditions
● Tests around bugs
● Tests around regressions
6. @nikhilwanpal | NikhilWanpal
How many tests?
● Coverage:
○ A metric showing how much of the code was ‘covered’ during the tests
○ Given tests pass, all paths that were traced by the control flow while the tests were running.
○ Many ways to measure:
■ Line
■ Function
■ Class
■ File
■ Statement
■ Branches
○ Can still miss out on ‘important’ issues and is also easy to fake.
● Confidence: How confident are you of your code, could be a better measure.
● Peer Confidence could be even better: How confident are you about your peer’s code?
7. @nikhilwanpal | NikhilWanpal
Test pyramid
Unit Tests
Number
of tests
Coverage
per test
Software
Behaviour
spec
Usefulness:
● Problem
Solving
● Debugging
● Refactoring
● Onboarding,
Learning Significance
from Business
Perspective
Integration Tests
System Tests
Acceptance
Tests
8. @nikhilwanpal | NikhilWanpal
Design influence
● Just enough code, just enough tests
● Extracting, Reuse
● Interfaces, de-coupling
● IOC: DI
● Strategies that help isolating the unit under test from the rest of the system
○ Stub: canned responses,
○ Fake: shortcut calculations, limited ability
○ Mock:
■ programmed expectations from specific calls they are to get
■ A complex, best avoided way of isolation
9. @nikhilwanpal | NikhilWanpal
Debugging
● A process of removing bugs
● Not a process of testing
● Not a process of development
● Not a method of execution
● Provides ways to see inside of the system and halt the flow at a given time /
statement or condition.
● Difficulties in non-linear executions