I am trying to mock an instance method within a real object which is injected within my Test class in spock
and I am using Micronaut (with Java) for writing my application. It is as follows:
class MyTestClass extends Specification {
@Subject
@Inject
ClassUnderTest classUnderTest
Event sampleEvent = getMockEvent();
def "test1" () {
given:
def classUnderTestSpy = Spy(classUnderTest)
when:
def res = classUnderTestSpy.callTestMethod(sampleEvent)
then:
1 * classUnderTestSpy.isRunning(_ as Long) >> {
return false
}
res != null
}
def getMockEvent() {
new Event(/* Some attributes here */)
}
}
The ClassUnderTest
is something like this:
@Singleton
class ClassUnderTest {
@Inject
Class1 class1Instance;
@Value("${com.myapplication.property}")
Integer value;
Object callTestMethod(Event event) {
// Some code
boolean isRunning = isRunning(event.id);
// Rest of the code
}
public boolean isRunning(Long id) {
return SomeOtherClass.staticMethod(id);
}
}
Whenever the isRunning
method is called the real SomeOtherClass.staticMethod()
method call happens and the isRunning
method returns true not false. Is there anyway I can Spy
the injected ClassUnderTest
instance and mock the instance method?