mercredi 2 septembre 2015

How can I have a unit test that ensures all subclasses implement a method?

I want to make a unit test that will ensure that all subclasses implement a method.

Some code may better explain what I am trying to do.

The super class is like this:

Class SuperClass
{
    public boolean isImportant()
    {
        throw customException;
    } 
}

Now say that I have sub classes a and b.

I'd like to ensure that this is included in those classes, so like:

Class A
{
    @override
    public boolean isImportant()
    { 
        return true;//or false watevs
    }
}

and class b:

Class B
{
}

Now if I do B b = new B(); b.isImportant() I will get the exception.

Instead of having a test for each class (there are many and I may miss some and in the future more subclasses may be added), how can I easily test this.

I am thinking if there is someway to instantiate a object of every subclass.

Something like this:

for(Class subClass : SuperClass.subclasses)
{
   subClass obj = new subClass();
   obj.isImportant();
}

as this will iterate through all the subclasses regardless of if some are added ore removed and will fail if there is an exception thrown.

Is there some way to do this?

Aucun commentaire:

Enregistrer un commentaire