1

I'm trying to test a simple method.

I have this class:

class Cloud @Inject constructor(var posx: Double = 0.0, var posy: Double = 0.0, var velocity: 
    Double = 1.0, val context: Context){

    val image: Bitmap = BitmapFactory.decodeResource(context.resources, R.raw.cloud)

    fun updateVelocity(){
        velocity += 5.0
    }

    fun draw(canvas: Canvas){
        canvas.drawBitmap(image,posx.toFloat() - (image.width / 2),posy.toFloat(),null)
    }    
}

I want to unit test the updateVelocity() method but i can't figure out how, should i use an instrumental test and pass the context or can i use something like mockk?

Can i do this with mockk?

@Test
fun cloudVelocity() { 
    val cloud: Cloud = mockk()                
    //update cloud velocity
    //assert that the velocity changed 
}

1 Answer 1

1

In this case is very hard to unit test yours class because it depends not only on context, but also on Bitmap, BitmapFactory and Canvas.

Maybe will be better if you separate business and drawing logic at different classes. For example yours Cloud object will contain only pure business logic and you could easily test it. On the other hand you could create CloudDrawer class that will contain drawing logic with Canvas/Context/Bitmap

In most simper cases you could replace Context by using special interface. For example we use getString() in our classes. But we want to test these classes. And in this case we use this abstraction over Context:

interface ResourceManager {
    fun getColor(@ColorRes resId: Int): Int
    fun getDrawable(@DrawableRes resId: Int): Drawable?
    fun getString(@StringRes resId: Int): String
    fun getString(@StringRes resId: Int, vararg formatArgs: Any): String
    fun getStringArray(@ArrayRes resId: Int): Array<String>
    fun getQuantityString(@PluralsRes resId: Int, quantity: Int, formatArgs: Int): String
}

And it's easy to mock this interface:

 val resource = mock(ResourceManager::class.java)
 `when`(resource.getString(any(Int::class.java))).thenReturn("text")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.