ArgumentCaptor in practice
Tests are very important. The use of frameworks, api have increased in the last years and thus with more integration points.
ArgumentCaptor came in this scenario where we need to capture some value sent to another class.
1. Definition
Use it to capture argument values for further assertions.
2. Example
In order to illustrate, I created a model based on Ticket (I don’t have experience on that), and the target is to show the ArgumentCaptor on PaymentService class.
Inside the TicketService there is a logic to apply the discount and send the value to Payment. Abstracting the complexity, let’s imagine (John Lenon), the target of the test should guarantee the correct discount applied when paymentService.pay is called.
To check this, use the ArgumentCaptor and tackle this problem 😎.
3. Conclusion
Using ArgumentCaptor, is easy, fast and safe to change the code, add new code and complete your task 📕.
4. Tech stack
- Java 11
- JUnit 5
- Lombok
- AssertJ
- Mockito