Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing abstract class throws InstantiationException

It's the first time I've written JUnit tests and I came across the following problem. I have to write the tests for an abstract class and I was told to do it this way: http://marcovaltas.com/2011/09/23/abstract-class-testing-using-junit.html

However, when I try to run the first test I get an InstantiationException like this:

java.lang.InstantiationException
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)

Here's the test I'm running:

/**
 * Test of setNumber method, of class BaseSudoku.
 */
@Test
public void testSetNumber_3args() {
    System.out.println("setNumber");

    BaseSudoku b = getObject(9);
    boolean expResult = false;
    boolean result = b.setNumber(0, -7, 7);
    assertEquals(expResult, result);            
}

Note that Base Sudoku is an Abstract Class and HyperSudoku is a child.

I have implemented the following abstract method in BaseSudokuTest:

protected abstract BaseSudoku getObject(int size); 

And here's the implementation in HyperSudokuTest that extends the BaseSudokuTest:

@Override
protected BaseSudoku getObject(int size) {  //I need size for other implementations 
    return new HyperSudoku();
}
like image 476
syfantid Avatar asked Jan 17 '14 15:01

syfantid


1 Answers

You've stated that BaseSudokuTest has an abstract method and is therefore abstract itself.

Assuming you are running your tests through BaseSudokuTest, Junit uses reflection to create an instance of your test class. You cannot instantiate abstract classes, whether directly or through reflection.

Move your abstract method to some other class. Your JUnit test class cannot be abstract.

Or rather run your HyperSudokuTest class. It will have inherited the @Test methods from BaseSudokuTest.

like image 107
Sotirios Delimanolis Avatar answered Nov 07 '22 07:11

Sotirios Delimanolis