androidjunitmockitoandroid-testingmockito-kotlin

How to mock a system class for type casting


I have the following code to get the current system memory:

val memClass = (context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).memoryClass

My initial goal is to return an Int value for it in testing. Something like this:

whenever((context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).memoryClass)
.thenReturn(500)

Since its a jUnit test and involves using the Context, I ended up mocking everything:

val context: Context = mock()

val activityService: Service = mock()

whenever(context.getSystemService(Context.ACTIVITY_SERVICE))
            .thenReturn(activityService)

whenever((context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).memoryClass)
            .thenReturn(500)

Now the problem is Mockito can't create a typecast for ActivityManager and throwing this error:

java.lang.ClassCastException: android.app.Service$MockitoMock$594525704 cannot be cast to android.app.ActivityManager

I also tried mocking the ActivityManager but it can't be used as a typecast:

enter image description here

I don't have a specific requirement to stick with the current solution. I will appreciate a better approach to my initial goal.


Solution

  • Maybe we have a misunderstanding. What I am talking about was this:

    val context: Context = mock()
    
    val activityService: ActivityManager = mock()
    
    whenever(context.getSystemService(Context.ACTIVITY_SERVICE))
                .thenReturn(activityService)
    
    whenever((context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).memoryClass)
                .thenReturn(500)
    

    As far as I understand: context.getSystemService( ... ) returns an Object.

    There is no relation between the classes android.app.ActivityManager and android.app.Service.


    Edit:

    The last line might need to be replaced with the equivalent of
    (the given code is probably not be the correct kotlin syntax)

        when(activityService.memoryClass).thenReturn(500);