2

How do I create a JUnit test that tests an abstract code from another class? I have an Abstract class called AbstractCurve and a "producer and consumer curve" that extends the abstract curve. The ConsumerCurve and ProducerCurve are the same but different class name. Here is the code:

public abstract class AbstractCurve {
    ArrayList < Point > myCurve = new ArrayList < Point > ();

    public AbstractCurve(int np, double m, double b, int dx) {
        for (int i = 0; i < np; i++) {
            int x = i * dx;
            double y = m * x + b;
            if (y < 0) throw new IllegalArgumentException();
            ArrayList < Point > myCurve = new ArrayList < Point > ();
            myCurve.add(new Point(x, y));
        }
    }

    public boolean add(Point p) {
        myCurve.add(p);
        sort();
        return false;
    }

    public void delete(Point p) {
        myCurve.remove(p);
    }

    public abstract void sort();

    public String toString() {
        String t = " ";
        for (int i = 0; i < myCurve.size(); i++) {
            t = t + myCurve.get(i).toString() + " ";
        }
        return t;
    }

    public int contains(Point p) {
        for (int index = 0; index < myCurve.size(); index++) {
            myCurve.equals(index);
        }
        return -1;
    }
}

Consumer:

public class ConsumerCurve extends AbstractCurve{
    public ConsumerCurve() {
        super(0, 0, 0, 0);
    }
    public void sort() {}
}
Jorge Campos
  • 22,647
  • 7
  • 56
  • 87
retrogirl19
  • 121
  • 10
  • 4
    You don't, test the extending classes. on your case `ConsumeCurve`. By the way, your question is a duplicate: http://stackoverflow.com/questions/7569444/how-to-test-abstract-class-in-java-with-junit – Jorge Campos Sep 23 '15 at 02:55
  • So I test the ConsumerCurve and ProducerCurve? – retrogirl19 Sep 23 '15 at 02:56
  • 1
    @retrogirl19 Yes, You would need to write JUnit for the subclasses. JUnit is for testing the functional aspect of a module and thus, by testing subclasses that inherits the behavior from parent `abstract` class does the purpose. – Karthik R Sep 23 '15 at 04:04

2 Answers2

0

You can't instantiate abstract classes so you can't test them directly. While testing existing subclasses would probably work, personally I'd create a mock subclass just for testing, so you know your subclass doesn't override any of the concrete methods, and even if an existing subclass doesn't override a concrete method today, someone might modify the subclass in the future in such a way to allow the test to still succeed but no longer be actually testing anything.

blm
  • 2,379
  • 2
  • 20
  • 24
-1

You can not create an object of an abstract class, but you can create objects of concrete subclasses.

The code you have written in AbstractCurve is inherited by your concrete subclasses ConsumerCurve and ProducerCurve, so you should write your tests for these classes.

Stormfjes
  • 83
  • 1
  • 1
  • 8