- A
unit testis a practice by whichsmall units of codeare 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.
- Tests are typically expressed as a combination of three clauses:
Givensome contextWhensome action is carried outThenconsequences should be observable
// Given
String name = "Tariq";
Integer age = 40;
Person tariq = new Person(name, age);
// When
String getNameResult = tariq.getName();
Integer getAgeResult = tariq.getAge();
// Then
Assert.assertEquals(name, getNameResult);
Assert.assertEquals(age, getAgeResult);-
Givenis 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 = "Tariq";
Integer age = 40;
Person tariq = new Person(name, age);Whenis the section of a unit test method that- invokes the method with the previously arranged parameters
// When
String getNameResult = tariq.getName();
Integer getAgeResult = tariq.getAge(); Thenis 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);