Home Kotlin, PowerMock, and `when`
Post
Cancel

Kotlin, PowerMock, and `when`

TLDR; Wrap when in backticks to make it work.

1
2
3
// stubbing Unirest and returning a mock response
`when`(Unirest.post(Mockito.anyString()))
    .thenReturn(httpRequestWithBody)

PowerMock is an extremely useful library for testing JVM applications. It makes mocking static members simple and plugs right into Mockito. I’ve used this library quite a bit in the past for pure Java projects and saw no reason to use it for testing a Kotlin project targetting the JVM.

Most of the setup is identical to what the Java test class would look like. However, Kotlin uses adds some reserved words on top of those used by Java. In particular, the when expression is generally an improvement on switch. See the below example.

1
2
3
4
5
6
val numberText = when(integerValue) {
  0 -> "It's zero"
  in 1..10 -> "It's single Digits"
  in 10..20 -> "It's in the teens"
  else -> "I'm not making a comprehensive set"
}

The match operator has three major advantages over switch. It can accept expressions (in 1..10) as well as single values (0). It requires the matches to be exhaustive (else). And there is no risk of fallthrough (no break).

Unfortunately, this useful operator does interfere with the PowerMock library, which implements a when method that can be used for stubbing methods. Using this method as you would in Java results in a compilation error.

Luckily, Kotlin provides a facility for working around this issue (as well as any other reserved work conflicts). Wrapping the when in backticks (`) will allow the PowerMock method to be called as expected.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@RunWith(PowerMockRunner::class)
@PrepareForTest(Unirest::class)
class LoginServiceTest {
    /**
     * Create Mocks for use in stubs and elsewhere
     */

    @Before
    fun setup() {
        mockStatic(Unirest::class.java)

        `when`(Unirest.post(Mockito.anyString()))
            .thenReturn(httpRequestWithBody)
    }
    /**
     * Post method is mocked for remaining tests
     */
}

Thanks for Reading!

-->