Testing abstract class throws InstantiationException

China☆狼群 提交于 2020-01-14 08:48:30

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/21190019/testing-abstract-class-throws-instantiationexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!