What’s the recommended way to mock or stub out a method to prevent its execution during a unit test?
My custom task class prepareWorkspace class calls clean, updateTools, checkout in its action. I want to stub out the updateTools method during unit testing of the class. The following meta trick works in standard groovy but not in my unit test.
Unit Test
...
SVNTestBase.prepTask.metaClass.updateTools = { println "mocked"}
SVNTestBase.prepTask.updateTools()
SVNTestBase.prepTask.prepWorkspace()
// updateTools should do nothing
Class
public class WorkspacePrepTask extends DefaultTask {
...
@TaskAction
void prepWorkspace() {
logger.lifecycle("prepWorkspace:\n\trepos: ${repositoryPath}\n\tlocal: ${localPath}\n\trev: ${buildRevision}\n------------------\n")
updateTools()
clean(localPath)
update(repositoryPath, buildRevision, localPath)
check(localPath)
}
...
void updateTools() {
File toolsDir = ToolsPath.getToolsDir()
LogManager.getRootLogger().info("Updating Tools Directory - ${toolsDir}")
scm.updateSvnWorkingCopy(ToolsPath.getToolsScmPath(), 'HEAD', toolsDir)
}