powermock / powermock

PowerMock is a Java framework that allows you to unit test code normally regarded as untestable.
Apache License 2.0
4.16k stars 586 forks source link

Kotlin Lambda fails parsing with Power-Mockito2 #965

Open ebi-igweze opened 5 years ago

ebi-igweze commented 5 years ago

When running with PowerMockito 2, files with lambda expressions fail to parse and I get the following error

java.lang.IllegalStateException: Failed to transform class with name com.example.domain.CaseTest. Reason: [source error] ) is missing

// when you try something like this
val lambda = { it: String ->
    // do something funny
}

// or something like this with mockito
doAnswer { it:InvocationOnMock ->
    val arg1 = it.arguments[0]
    // do something funny
}.`when`(mockedObj).member(any())

It produces the error when you try using lambda expression like the ones defined above. I have to use the following work around, what I had to do was create a member function for the test and pass it as a parameter. For instance



// define the function like so
private fun doSomething(it:InvocationOnMock) {
   val point = it.arguments[0]
   // do something funny
}

// then pass the function like so
whenever(defaultDisplay.getSize(any())).then(::doSomething)
TWiStErRob commented 5 years ago

@ebi-igweze this won't solve the problem, but may be a better workaround: try function-local functions, if they work you can at least keep those functions close to usage and maybe even access local variables.

eljonny commented 5 years ago

This is also an issue in Java 8. Wrapping lambdas in getters works around the problem, but it looks to be at least related to this, if not actually being the same issue. I've had to work around this 3 or so times at work in the last 6 months, and it originally took me about 7 hours of debugging to figure out that this is actually the cause.