What have we learned so far
Part 1 – What is Unit Testing?
https://www.onlyfullstack.com/what-is-unit-testing/
Part 2 – What is JUnit? How to use JUnit?
https://www.onlyfullstack.com/what-is-junit-how-to-setup-junit-in-eclipse/
Part 3 – Annotations used in JUnit
https://www.onlyfullstack.com/part-3-annotations-used-in-junit/
Assert Methods
This class provides a set of assertion methods, useful for writing tests. Only failed assertions are recorded. We will be writing the test cases for below class:
@Test public void assertEquals_example() { Employee employeeNew = new Employee(); employee.setSalary(1000000.0); assertEquals("EMPLOYEE OBJECT", employee, employeeNew); }
@Test public void assertTrue_assertFalse_example() { assertTrue("VALID EMPLOYEE OBJECT", employeeService.isValidEmployee(employee)); assertFalse("INVALID EMPLOYEE OBJECT", employeeService.isValidEmployee(null)); }
The assertNull() and assertNotNull() methods test a single variable to see if it is null or not null. Here is an example:
@Test public void assertNull_assertNotNull_example() { assertNotNull(employeeService.getEmployeeFromId(1)); // in EmployeeService we have a map with // single entry of key as 1 so here we will get employee object assertNull(employeeService.getEmployeeFromId(2)); // We will get null as response }
@Test public void assertSame_assertNoSame_example() { assertSame(employeeService.getEmployeeFromId(1), employeeService.getEmployeeFromId(1)); assertNotSame(employee, employeeService.getEmployeeFromId(1)); // We will get null as response }
@Test public void assertThat_example() { assertThat(employeeService.getEmployeeFromId(1), is(employeeService.getEmployeeFromId(1))); assertThat(employeeService.getEmployeeFromId(1), is(CoreMatchers.notNullValue())); }
Source Code
Download the source code of JUnit tutorial from below git repository :
unit-testing-and-integration-testing-with-spring-boot
Let’s go to our next tutorial where we will discuss below points :
Part 5 – Complete guide for Hamcrest JUnit
In this tutorial we will understand below topics-
– Hamcrest Matcher Tutorial
– The Core Matchers
1. CoreMatchers.is(T value)
2. CoreMatchers.not(T value)
3. CoreMatchers.startsWith(String prefix) & CoreMatchers. endsWith(String suffix)
4. CoreMatchers.containsString(String substring)
5. CoreMatchers.notNullValue()
6. CoreMatchers.sameInstance(T target) & CoreMatchers.instanceOf(Class<?> type)
– Number Matcher
1. Matchers.greaterThan(T value) Matchers.greaterThanOrEqualTo(T value)
2. Matchers.lessThan(T value) Matchers.lessThanOrEqualTo(T value)
– Collection Matcher
1. Matchers.empty()
2. Matchers.hasSize(int size) and Matchers.hasItem(T item)
3. Matchers. hasKey(K key), Matchers.hasValue(V value) & Matchers.hasEntry(K key, V value)