logic or ways to check if code logic performs as expected
Two Main Types:
- Unit Testing: testing of individual behaviors on different functional groups within an application (JUnit + Mockito)
- Integration Testing: testing correct overall functionality of multiple functional groups interacting within an application
- Accept Testing (UAT): verify the entire application including UI (Through UI)
Why Testing
- Quality of Code: ensures existing logic is not broken by additional features as the application grows
- Documentation
- Test Driven Development: writing test cases before actual code, ensure the developer thinks thoroughly about business requirements and logic
![[Pasted image 20260113125505.png]]
Testing Scenarios
Mockito is used to mock interface so that dummy functionality can be added to mock interface that can be used in unit testing
- When testing the controller layer, we only want to focus on testing (fake object on real interface)
Mockito - Basic Annotations
- @Mock
- It helps to create a Mock object, where we can stub/simulate the behavior of the object
- It takes a Class as its parameters
- @Spy
- It helps to create a Partial Mock object, where methods will be directly invoked unless those methods are stubbed
- It takes an Instance as its parameter
- @InjectMocks
- It injects mock fields into the object that needs to be tested automatically
- It takes a Class as its parameter
Stubbing: Configure the mock and define what to do when specific methods of the mock are called
when(xxx.method()).thenReturn()
doReturn().when(xxx).method()
when().thenCallRealMethod()
when().thenThrow()
Verify
- Once a mock or spy has been used, we can verify that specific interactions took place
- syntax
verify(mock, VerificationMode)
Testing in Repository
- verify our queries that retrieve, insert, update, and delete data
- call the database, but, without affecting the actual data
- Annotations
- @DataJpaTest – load only the repository
- @TestMethod(MethodOrder.OrderAnnotation.class) – Specify which test cases need to run first
- @ActiveProfiles – Specif another profile that needs to be used during the test
- @Order – On the method level, define the order of test cases
- @Rollback – Spring will roll back all data changes
Test Driven Development
Code Coverage
- Code coverage is a software metric used to measure how many lines of our code are executed during automated tests
- JaCoco is a good tool to check the testing code coverage
Test first
- create test case first
- developers create codes to meet test case requirements
- move to the next failed test case