Search code examples
javaunit-testinginheritancejunitsubclass

Set a variable of superclass while testing subclass in Junit


I have a class A and a class B which extends class A

class A{
    protected String x = "";
    Method (){
    x = "val";
    }
}
class B extends A{
     // Uses x in a method
}

If I write Junit test case for a method in class B, I get value of x as an empty string "" as set while declaration. Is there a way to set the value for x to "val" while testing class B method?


Solution

  • Given the new scope of the question, you should be able to set x by creating an object of type B (bObject) then calling Method() from A.

    B bObject = new B();
    bObject.Method();

    This would set X given the methodology you show in your question. You could also say

    B bObject = new B();
    bObject.setX(str);

    Where str represents whatever you want x to be for your test case. This assumes you have x set up with a getter and setter in A, which is generally best practice.