测试抽象类抛出InstantiationException [英] Testing abstract class throws InstantiationException

查看:411
本文介绍了测试抽象类抛出InstantiationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次编写JUnit测试,遇到了以下问题.我必须为抽象类编写测试,并被告知要这样做: http://marcovaltas.com/2011/09/23 /abstract-class-testing-using-junit.html

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

但是,当我尝试运行第一个测试时,会得到如下所示的InstantiationException:

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

请注意,基础数独是一个抽象类,而HyperSudoku是一个子类.

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

我在BaseSudokuTest中实现了以下抽象方法:

I have implemented the following abstract method in BaseSudokuTest:

protected abstract BaseSudoku getObject(int size); 

这是HyperSudokuTest中的实现,它扩展了BaseSudokuTest:

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

推荐答案

您已经说过BaseSudokuTest具有abstract方法,因此本身就是abstract.

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

假设您正在通过BaseSudokuTest运行测试,Junit会使用反射来创建测试类的实例.您不能直接或通过反射实例化抽象类.

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.

将您的抽象方法移至其他类.您的JUnit测试类不能为abstract.

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

或者运行HyperSudokuTest类.它将从BaseSudokuTest继承了@Test方法.

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

这篇关于测试抽象类抛出InstantiationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆