Unit test SparseArray using JUnit (using JVM)

Unmock is a really nice project that gives you this and more. https://github.com/bjoernQ/unmock-plugin

Just add the plugin and it will work.


In case anyone is still looking, you don't need any third party libraries. You can simply mock SparseArray.

Create a file SparseArray.java inside app/src/test/java/android/util and paste the following:

package android.util;

import java.util.HashMap;

public class SparseArray<E> {

    private HashMap<Integer, E> mHashMap;

    public SparseArray() {
        mHashMap = new HashMap<>();
    }

    public void put(int key, E value) {
        mHashMap.put(key, value);
    }

    public E get(int key) {
        return mHashMap.get(key);
    }
}

Note: In case you are using funcations beside put and get you will need to implement those here as well.


There's an equivalent implementation of SparseArray in Support Library called SparseArrayCompat that can be used in JVM Unit Tests. Also it has more features than the native one, so you're better off using that.