2

Language: Kotlin

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)

echen
  • 2,002
  • 1
  • 24
  • 38
  • 5
    You write a higher-level abstraction that uses System.getenv internally, and inject that higher-level abstraction in all your code, which allows you to easily mock this abstraction when testing the functional code. – JB Nizet Oct 20 '19 at 13:55
  • 1
    That is what I eventually had to do ... which is fortunate since I own the code that is being tested and had the ability to refactor it. The reason I asked this question is b/c usually one shouldn't be writing code such that using `staticMockk` is necessary ... however - it often becomes necessary when writing tests against a legacy codebase that does make use of static methods on something as invasive to mock as "System" ... so I was wondering if there was a mechanism to essentially "spy" on it – echen Oct 20 '19 at 19:05
  • 1
    Simple answer: "don't do mocking of System if you can". If it hangs it is most probable super hard to fix on MockK side out of my experience, so I wouldn't hope that. – oleksiyp Oct 20 '19 at 20:25

0 Answers0