Counting times a function is called via JUnit

265 Views Asked by At

I want to count how many times I make a HTTP GET when I use websockets and when I do not use websockets. I expect once when using websockets and n-times otherwise. I want to do this via JUnit, and I happen to be using Spring too. Are there any creative ways to count the times I make a GET with Jersey?

client.target(.....).get(....)

I don't know how to do this without cluttering my production code with test specific code.

2

There are 2 best solutions below

0
On BEST ANSWER

If you code is defined using an interface, then I would use a Decorator pattern to add additional behavior. In this case additional behavior would be keeping track of the count of calls.

This approach is easy to configure if your concrete class is configured through Spring. Then in your Spring resource for the JUnit test, modify it to inject the Decorated class. There is no impact to existing production code.

0
On

If you add one static variable COUNT and increment it with every call - it will not hurt production at all. And you can use this variable not only for unit testing but even for production monitoring.