1

I am unit testing a class with the following structure.

public class Experiment {

    private final Map<String,String> map = new HashMap<>();

    Experiment(Set<String> set){
        for(String str :set ){
            map.put(str,str);
        }
    }

    public String getVal(String str){
        return map.get(str);
    }

}

As seen my class has only one instance variable that is a HashMap. Now i want to make sure my map is correctly populated through my constructor which takes a HashSet. Since I can create a expected Map structure independently. But i am stuck now because my 'map' is "private" in my class. I dont want to expose my state variable to outside world by making it public. Please suggest a way to Unit test my map variable.

3 Answers 3

1

You could access to your map variable through Reflection but it's NOT a good practice to test your private implementation details directly. The better approach would be to test the public API that depends on that private stuff. In your case test whether getVal method returns the same value you added to the map or not. Read more on.

1

What I personally do is make the field package-private. And I annotate it with Guava's @VisibleForTesting.

But that's only when I'm testing the internal state. Usually, you want to test what the public API (usually public and protected members) offer.

1

If Experiment is meant to be a map-like object you could extend use google/guava and extend ForwardingMap. See Forwarding Decorators in CollectionHelpersExplained · google/guava Wiki for details.

e.g.

public class Experiment extends ForwardingMap<String,String> {
    private final Map<String,String> map;

    Experiment(Set<String> set){
        Map<String,String> map = new HashMap<>();
        for(String str :set ){
            map.put(str,str);
        }
        this.map = Collections.unmodifiableMap(map);
    }

    @Override
    protected Map<String, String> delegate() {
        return map;
    }

    public String getVal(String str){
        return map.get(str);
    }
}

This will make Experiment implement Map so that publicly you can call things like get(Object), containsKey(Object), entrySet(), etc. but calling any modifier methods like put(String, String) will throw an exception. Then you can compare Experiment with any other Map in your tests to compare the key-value entry sets.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.