2
votes

Say I have a java class like so

public class UnderTest {
   public void method1() { 
      callRealMethod();
  }
}

I want to create a spy object and modify the behavior of the method. I found a code example for doing it in in groovy using the Spock testing framework like this:

UnderTest underTest = Spy() {
      method1() >> {
        callRealMethod()
        timesExecuted++
      }
}

How can I do that in Java instead of Spock/Groovy?

1
Do you want to count calls or do something else? - Antoniossss
Yes, just to count calls - draca
It should be noted that the official documentation pretty much recommends not using spys at all: "Real spies should be used carefully and occasionally, for example when dealing with legacy code." - daniu

1 Answers

1
votes

Use eg Mockito to count invocation count.

UnderTest spiedInstance=Mockito.spy(realInstance)

verify(spiedInstance,times(x)).method1();