简体   繁体   中英

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();
}

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 .

I hit a similar issue, which was caused by adding my abstract test class to a TestSuite:

import junit.framework.TestSuite;

public class AllTests {
    public static TestSuite suite(){
        TestSuite suite = new TestSuite();
        suite.addTestSuite(SessionTest.class); // Abstract class
        suite.addTestSuite(CourseSessionTest.class); // Extends SessionTest        
        return suite;
    }
}

Taking SessionTest.class out of my TestSuite fixed my problem because I was attempting to instantiate an abstract class by adding it to the suite (which was where the errors were coming from) and the CourseSessionTest was calling all of the methods in it anyway.

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