构造函数调用必须是具有继承的构造函数中的第一个语句

时间:2016-10-27 14:00:03

标签: java junit constructor junit4 super

我有我的父抽象JUnitTest类:

public abstract class RestWSTest
{

  public RestWSTest()
  {
  }

  @Before
  public void setUp() throws Exception
  {
    ...
  }

  @After
  public void tearDown() throws Exception
  {
    ...
  }
}

然后我希望有一个扩展RestWSTest的类,如下所示:

public class RestWSCreateGroupTest extends RestWSTest
{

  public RestWSCreateGroupTest()
  {
    super();
  }

  @Before
  public void setUp() throws Exception
  {
    super(); -->   *Constructor call must be the first statement in a constructor*
    ...
  }

  @After
  public void tearDown() throws Exception
  {
    super(); -->   *Constructor call must be the first statement in a constructor*
    ...
  }

  @Test
  public void testCreateGroup()
  {
  ...
  }
 }

为什么我收到错误消息?我有一个构造函数,在那里我调用super(),所以我真的不知道该怎么做......

2 个答案:

答案 0 :(得分:2)

方法public void setUp()不是构造函数。你不能在里面打电话给super();。我想你打算super.setUp();

答案 1 :(得分:2)

您无法在构造函数方法之外使用super()调用。

换句话说,setUp()和tearDown()是方法,它们不是构造函数,因此你不能使用super()调用。

相反,您可以使用以下语法访问/调用超类方法:super.mySuperClassMethod();

所以改变你的代码如下:

public class RestWSCreateGroupTest extends RestWSTest
{

  public RestWSCreateGroupTest()
  {
    super();
  }

  @Before
  public void setUp() throws Exception
  {
    super.setUp();
    ...
  }

  @After
  public void tearDown() throws Exception
  {
    super.tearDown();
    ...
  }

  @Test
  public void testCreateGroup()
  {
  ...
  }
 }

有关详细信息,请参阅以下链接: https://docs.oracle.com/javase/tutorial/java/IandI/super.html

相关问题