Sobes.tech
Junior — Middle

Can you explain what is meant by the Spy component in testing and development?

sobes.tech AI

Answer from AI

In the context of testing and component development, a Spy is a special object or function that records information about calls made to it, so that later it can be checked how exactly interactions with this component occurred.

A Spy is similar to a mock, but usually does not completely replace the behavior of an object, only tracks calls (for example, how many times a method was called, with what parameters).

Example of using a Spy in Java:

public class SpyExample {
    public static class Service {
        public void performAction(String param) {
            // Real logic
        }
    }

    public static class ServiceSpy extends Service {
        public int callCount = 0;
        public String lastParam = null;

        @Override
        public void performAction(String param) {
            callCount++;
            lastParam = param;
            super.performAction(param); // Can call or not
        }
    }

    public static void main(String[] args) {
        ServiceSpy spy = new ServiceSpy();
        spy.performAction("test");
        System.out.println("Calls: " + spy.callCount); // Calls: 1
        System.out.println("Last parameter: " + spy.lastParam); // Last parameter: test
    }
}

Thus, a Spy helps to verify how and with what data interactions with the component occurred, without drastically changing its behavior.