简体   繁体   中英

Private Inner class needed for Outer class testing?

I have an outer class, Outer, and an inner class, Inner. For testing a public method, outerMethod(), in Outer I need to create an instance of an Inner, which will be stored in a list called inners. The inner class is a modified version of another class, Other.

To overview:

class Other{
    public Other(){
       //doesnt matter actual implementation
    }
}

class Outer{
    private List<Inner> inners = new ArrayList<Inner>();

    public Outer(){}

    public void outerMethod(){}

    private class Inner{
        public Inner(Other other){}
    }
}

My question is should I create a method like the following just for testing purposes.

public void createInnerInstance(Other other)
{
    Inner inner = new Inner(other);
    inners.add(inner);
}

Is there any other workaround for this? Now I can make Inner public but Outer is the only class that really uses Inner.

Regards

Changing code specifically for testing purposes is probably not a very good idea.

You've got two options - either to redesign your class as @bot suggests in comments, or to apply workarounds.

You could change field/inner class access modifiers and use them from your test instead. Take a look here , and here for implementation details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM