https://kotlinlang.org logo
#android
Title
# android
e

Ellen Spertus

03/23/2020, 8:56 PM
I’m having trouble mocking
ActivityInfo.exported
with Mockito. Here’s the relevant part of my code:
Copy code
private fun makeResolveInfo(appName: String, packageName: String, exported: Boolean = true) : ResolveInfo {
    val activityInfo = mock(ActivityInfo::class.java)
    `when`(activityInfo.exported).thenReturn(exported)
    // code omitted
}
The error is:
Copy code
org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
   Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
Here is the javadoc for the
exported
getter (which is in
ComponentInfo
, which
ActivityInfo
extends): https://developer.android.com/reference/android/content/pm/ComponentInfo#exported
m

mattinger

03/23/2020, 11:56 PM
Have you tried mockito-kotlin library? I've found it handles kotlin code infinitely better than straight up mockito. In addition, they use
whenever
instead of having to escape
when
e

Ellen Spertus

03/24/2020, 1:04 AM
Thanks, @mattinger! I’d been wondering just today if there was a way of avoiding escaping
when
.
m

mattinger

03/24/2020, 3:46 AM
escaping when isn't hard to do to be honest, you can just make a top level function for the syntax above, or an extension function to OngoingStubbing for the doXXX().when() type syntax
it's just not necessary if you use mockito-kotlin as it already contains all that along with other kotlin goodies such as a proper re-ified any() function
e

Ellen Spertus

03/24/2020, 5:59 PM
@mattinger I checked with my employer (Mozilla), and they’ve been switching to MockK, so I’ll probably do that. https://mockk.io/
(I’m the only Android programmer on my team, which is why I ask most of my questions here, rather than on the work Slack.)
m

mattinger

03/24/2020, 6:01 PM
that would be a huge undertaking for us. We're heavily vested in things like mockito and dagger mock. not even sure if dagger mock supports mockk
e

Ellen Spertus

03/24/2020, 6:09 PM
@mattinger May I ask where you work?
m

mattinger

03/24/2020, 6:15 PM
Comcast
e

Ellen Spertus

03/24/2020, 8:36 PM
@mattinger Thanks for keeping Internet access up.
2 Views