Search code examples
javamockingmockitojunit4powermock

How to test local variables inside java protected method


I am trying to find a way to test a local variable declared and initiated inside a protected method. This is my code. I would like to test the "id" with "someText" is being added to the context and removed in finally block. is there any way to test it in java? Any help is appreciated.

public abstract class BaseTransaction {

    protected Status handleTransaction() {

        Map<String, String> context = new HashMap();
        context.put("id","someText");

        try {
            //some other method calls
        } finally {
            context.remove("id");
        }

    }

}

Solution

  • You shouldn't test context, that's too low level, but if you insist, change the code to:

    protected Status handleTransaction() {
        Map<String, String> context = new HashMap<>();
        context.put("id", "someText");
        try {
            return handleContext(context);
        } finally{
            context.remove("id");
        }
    }
    protected Status handleContext(Map<String, String> context) {
        //some other method calls
    }
    

    You can now mock handleContext and call handleTransaction, to test that context map has correct content when handleContext is called.

    You can also call handleContext directly, to test that it reacts correctly with various content in the context map.

    Basically, you've split the logic of the original method into 2 units that can be independently tested.