Test Driven Development (TDD)
-
What is a unit test?
- A
unit test
is a practice by whichsmall units of code
are tested. - The purpose of a unit test is to determine if a feature being tested is fit for use in other parts of an application.
- It is considered best practice to test every method in an application with at least 2 sets of arguments.
-
What is a unit test?
- Tests are typically expressed as a combination of three clauses:
Given
some contextWhen
some action is carried outThen
consequences should be observable
-
Example
// Given
String name = "Leon";
Integer age = 25;
Person leon = new Person(name, age);
// When
String getNameResult = leon.getName();
Integer getAgeResult = leon.getAge();
// Then
Assert.assertEquals(name, getNameResult);
Assert.assertEquals(age, getAgeResult);
-
What are the three clauses of a test?
- Tests are typically expressed as a combination of three clauses:
Given
some contextWhen
some action is carried outThen
consequences should be observable
-
Given (some context)
Given
is the section of a unit test method that- initializes, instantiates, or sets the value of data to pass to test method.
- Example
// Given
String name = "Leon";
Integer age = 25;
Person leon = new Person(name, age);
-
When (some action is carried out)
When
is the section of a unit test method that- invokes the method with the previously arranged parameters
// When
String getNameResult = leon.getName();
Integer getAgeResult = leon.getAge();
-
Then (consequences should be observable)
Then
is the section of a unit test method that- verifies that the method to be tested behaves as expected
// Then
Assert.assertEquals(name, getNameResult);
Assert.assertEquals(age, getAgeResult);