Adding Unit Test
Locator API app follows Test Driven Development (TDD). Unit testing is an essential part of our application development. TDD ensures:
Improve in code quality
Developer can get instant feedback on the code. This will allow quick identification of issues and can be resolved before merging it to main branch.
Code refactoring.
Increase maintainability.
reduces cost.
Increases confidence.
Technology Used
JUnit Library
H2 (in-memory database)
Clover or JaCoCo (code coverage tools)
Creating a Test case
Create test classes for each operation. example: OrganizationUnitReadTest
Add
@RunWith
annotation to tellJUnit
to run the tests in Sprint test frameworkAdd
@Autowired
annotation to inject the necessary dependencies such as services and repository classes.Write test methods to test each operations. For example. in OrganizationUnitReadTest you might want to add method that reads the OrganizationUnits, read the response and asserts that there is properly formatted response.
Add
@Test
annotation to mark each test method as a test case.If there is any external dependencies, we can use mocking framework like Mockito and others to simulate the external dependencies.
Run the tests and ensure that they pass.
Example
:
@RunWith(SpringRunner.class)
@SpringBoottest
public class OrganizationUnitReadTest {
@Autowired
private OrganizationUnitService organizationUnitService;
@MockBean
private OrganizationUnitRepository organizationUnitRepository;
@Test
public void testRead() {
Long id = 1L;
OrganizationUnit oUnit = new OrganizationUnit();
oUnit.setName("Family Planning Outlet");
oUnit.setAddress("7901 Airport Blvd, Houston, TX");
oUnit.setId(id);
when(organizationUnitRepository.findById(id).thenReturn(Optional.of(oUnit)));
OrganizationUnit retriveOunit = organizationUnitService.read(id);
assertEquals(oUnit, retriveOunit);
verify(organizationUnitRepository, times(1)).findById(id);
}
}