/
Adding Unit Test

Adding Unit Test

Locator API app follows Test Driven Development (TDD). Unit testing is an essential part of our application development. TDD ensures:

  1. Improve in code quality

  2. 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.

  3. Code refactoring.

  4. Increase maintainability.

  5. reduces cost.

  6. Increases confidence.

Technology Used

  • JUnit Library

  • H2 (in-memory database)

  • Clover or JaCoCo (code coverage tools)

Creating a Test case

  1. Create test classes for each operation. example: OrganizationUnitReadTest

  2. Add @RunWith annotation to tell JUnit to run the tests in Sprint test framework

  3. Add @Autowired annotation to inject the necessary dependencies such as services and repository classes.

  4. 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.

  5. Add @Test annotation to mark each test method as a test case.

  6. If there is any external dependencies, we can use mocking framework like Mockito and others to simulate the external dependencies.

  7. 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); } }

Related content