Unit Testing
Introduction
What is a Unit Test
A Unit test is very small method that you write to test some part of your code.
public String isEmailValid(String email) { JUnit
Input Result
Unit Test
Input Result
Code that needs to be tested Unit Test
Input Result
Unit Test
}
Class Class
Unit Test Unit Test
Method Unit Test Method Unit Test
Unit Test Unit Test
Unit Test Unit Test
Method Unit Test Method Unit Test
Unit Test Unit Test
Class Class
Unit Test Unit Test
Method Unit Test Method Unit Test
Unit Test Unit Test
Unit Test Unit Test
Method Unit Test Method Unit Test
Unit Test Unit Test
Unit Test Example
public class Calculator {
public int integerDivision(int dividend, int divisor) {
return dividend / divisor;
}
@Test
void testIntegerDivision_whenValidValuesProvided_shouldReturnExpectedResult() {
//Arrange
Calculator calculator = new Calculator();
//Act
int result = [Link](4,2);
//Assert
assertEquals(2, result, "4/2 should have returned 2");
}
Class Class
Unit Test Unit Test
Method Unit Test Method Unit Test
Unit Test Unit Test
Unit Test Unit Test
Method Unit Test Method Unit Test
Unit Test Unit Test
Class Class
Unit Test Unit Test
Method Unit Test Method Unit Test
Unit Test Unit Test
Unit Test Unit Test
Method Unit Test Method Unit Test
Unit Test Unit Test
Mock HTTP Client
Class
All parameters are valid
Unit Test
HTTP Client.
Method Unit Test One parameter has invalid value
Dependency.
Unit Test
Invalid Response from HTTP Client
Method
Why write Unit Tests?
● Make sure that the code works,
● Code works with valid and invalid input parameters,
● Code works now and in the future,
● Other code still works even after you made changes.
Testing Pyramid
Testing software functionality from
3. End-To-End beginning to end
Testing / UI
Testing
Application code is tested
2. without mocking database or
Integration Tests HTTP connections
Testing isolated small
1. pieces of code with Fake or
Unit tests Mock dependencies