FAQ

Is it possible to inject own method implementation using Groovy reflection?

Q: I often see a situation where an easy test can be written but there are several internal methods calls inside the tested methods which need lots of mocked objects to be created. If I could mock those internally called methods that would help me a lot to be really focused on the main issue.

Groovy is a dynamic language so it should be possible. I was trying to do it using metaclass.methodName overriding but unsuccessfully. I don't have access to the TDD4C library source code, so I don't know if the tested class can be edited this way:

def script = testRun.getElementScript()
script.methodToBeOverriden = { return "test" }
script.testedMethod()


String testedMethod(){
def property = methodToBeOverriden()
if (property == "test"){
//do complicated logic
}


A: You can use spy() on testRun.getElementScript() and mock the method like you would do in Java, e.g.:

given:
TestRun testRun = TestRun.builder()
        .buildElementTest(LOGIC_DIR, ELEMENT_NAME)
Script script = spy(testRun.getElementScript())
script.someInternalMethod(any(), any())

when:
def result = script.someTestedMethod()


Beginner's FAQs

I would like to do X rather than this!

No please. https://8thlight.com/blog/uncle-bob/2012/01/11/Flipping-the-Bit.html

We don't have time do do this!

No one has.

Really?

Yes.

How to explain that this might be useful?

Feel free to use these slides:

Found an issue in documentation? Write to us.

Â