How can I detect that a gradle code is running inside a test?

I’m running tests for a Gradle plugin on Team City, and the plugin has a feature where it logs out the current project version to Team City itself, so that the build status reflects the version of the project using the plugin currently being built. This is done by logging a specially formatted string to stdout, based on project.version.

However, when running the tests for the plugin itself, this version is usually nonsense, or some default value that suits the test in question, but since the plugin is configured to log this version, it ends up changing the plugin’s Team City build status to all sorts of irrelevant values while the tests are running.

Since the logic determining if the output should be written or not is based on detecting that it’s running in Team City or not, it’ll always get enabled even when running tests, so I need some way of saying, if selfTest -> don’t log.

You could add a system property to the test task and then check for it in the plugin code. If using TestKit’s GradleRunner in the tests you can pass along the system property as needed or just set a system/project property using withArguments.

For example, I have some tests that need to disable certain repositories when the plugin is under test and the GradleRunner’s are configured to pass in a project property that the plugin checks for. The spock tests have a helper method similar to:

GradleRunner createRunner( String... arguments ) {
    return GradleRunner.create()
        .withPluginClasspath()
        .withProjectDir( projectDir.root )
        .withArguments( '-Pmy.plugin.repositories.disabled=true', *arguments )
}