I'm writing a Gradle plugin that interacts with an external HTTP API. This interaction is handled by a single class (let's call it ApiClient
). I'm writing some high-level tests that use Gradle TestKit to simulate an entire build that uses the plugin, but I obviously don't want them to actually hit the API. Instead, I'd like to mock ApiClient
and check that its methods have been called with the appropriate arguments, but I'm not sure how to actually inject the mocked version into the plugin. The plugin is instantiated somewhere deep within Gradle, and gets applied to the project being executed using its void apply(Project project)
method, so there doesn't appear to be a way to inject a MockApiClient
object.
Perhaps one way is to manually instantiate a Project
, apply()
the plugin to it (at which point, I can inject the mocked object because I have control over plugin instantiation), and then programmatically execute a task on the project, but how can I do that? I've read the Gradle API documentation and haven't seen an obvious way.
A worst-case solution will be to pass in a debug
flag through the plugin extension configuration, which the plugin will then use to determine whether it should use the real ApiClient
or a mock (which would print some easily grep-able messages to the STDOUT). This isn't ideal, though, since it's more fuzzy than checking the arguments actually passed to the ApiClient
methods.
Perhaps you could split your plugin into a few different plugins
my-plugin-common
- All the common stuffmy-plugin-real-services
- Adds the "real" services to the model (eg RealApiClient)my-plugin-mock-services
- Adds "mock" services to the model (eg MockApiClient)my-plugin
- Applies my-plugin-real-services
and my-plugin-common
my-plugin-mock
- Applies my-plugin-mock-services
and my-plugin-common
In the real world, people will only ever apply: 'my-plugin'
For testing you could apply: 'my-plugin-mock'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With