ArgumentCaptor in practice

Luiz Gustavo De O. Costa
2 min readJan 30, 2022

--

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.

Pac-Man as ArgumentCaptor

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.

Ticket class diagram

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.

TicketService class

To check this, use the ArgumentCaptor and tackle this problem 😎.

TicketServiceTest class

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

5. References

https://pixabay.com

--

--

Luiz Gustavo De O. Costa
Luiz Gustavo De O. Costa

Written by Luiz Gustavo De O. Costa

Hey friend!! I’m Luiz Gustavo, a Java developer and I’m here to learn and write about Java, tests and good practices

No responses yet