Reputation: 2072
The goal is to test a method that calls System.getenv
internally. I'd like to make this method produce a predefined result.
Tried:
mockkStatic(System::class)
every {
System.getenv(any())
} answers {
when {
firstArg() as String == "clientId" -> "aaa"
firstArg() as String == "clientSecret" -> "bbb"
else -> throw IllegalArgumentException("something went wrong")
}
}
mockkStatic(System::class)
This appears to have sent the JVM into a bit of tipsy:
Exception in thread "main" java.lang.StackOverflowError
Exception: java.lang.StackOverflowError thrown from the UncaughtExceptionHandler in thread "main"
How does one test a method like this? (as you can imagine, a lot of code uses environment variables)
Upvotes: 4
Views: 3678
Reputation: 24522
How about using the System Stubs library?
testImplementation("uk.org.webcompere:system-stubs-core:2.1.7") // Main artifact
testImplementation("uk.org.webcompere:system-stubs-jupiter:2.1.7") // For JUnit 5
Pay attention to the @ExtendWith(SystemStubsExtension::class)
:
@ExtendWith(SystemStubsExtension::class)
class ExampleTests {
@SystemStub
val systemProperties = SystemProperties()
@SystemStub
val environmentVariables = EnvironmentVariables()
@Test
fun `Example test`() {
systemProperties.set("os.name", "windows")
environmentVariables.set("MY_VARIABLE", "bunny")
// ...
}
}
Upvotes: 0