【问题标题】:JUnit - Use method in test from another classJUnit - 在另一个类的测试中使用方法
【发布时间】:2019-06-23 16:17:33
【问题描述】:

场景如下:

我有一个为项目的一部分执行测试的类。

public class section1 extends BaseTest {

    @Test
    public void test1() {
        //somecode
    }
}

问题是在 test1 中,我想使用在另一个测试类中定义的方法(我们没有在自动化项目中使用页面对象)。

public class section2 extends BaseTest {

    @Test
    public void test2() {
        //somecode
        methodOne();
    }

    void methodOne(){
        //somecode
    }
}

所以,我尝试创建一个实例并通过它访问该方法

section2 sec2 = new section2();
.
.
.
@Test
    public void test1() {
        //somecode
        section2.methodOne();
    }

但它一开始执行该方法就会抛出 NullPointerException。

然后,我尝试将类 section1 扩展到 section2 并使用该方法,因此它在此处执行该方法,但是一旦 test1 完成,它就开始从扩展类(在本例中为 test2)执行测试。

我该怎么做才能防止这种情况发生,或者有没有其他方法可以在不扩展和不公开该方法的情况下使用该方法?

【问题讨论】:

  • 将 methodOne() 移至 BaseTest - 为什么不呢?
  • 你能提到你在哪一行得到 NullPointerException
  • @BorLaze 因为它不仅是methodOne,它就像三个方法,它们用于填写结帐信息......你可以想象那些很长
  • @SameerArora 我在 test1 内的 Section1 类的行上得到它,在它执行方法的行上。它没有给我更多关于它在该方法中失败的信息

标签: java selenium methods junit automation


【解决方案1】:
Section 1 extends BaseTest

Section 2 extends BaseTest

你为什么不试试这个:

Section 2 extends Section 1

【讨论】:

  • 对不起,其实我写错了,但是在我试过的代码中:Section1 extends Section2 / Section2 extends BaseTest
【解决方案2】:

在 section1 类中添加以下代码:

section2 sec2;
@Before
public void initialize() {
    sec2 = new section2();
}

由于我们使用上面的 @Before JUnit 注释,这个“initialize()”方法将通过初始化“section2”类首先在那里执行。

@Test
public void test1() {
    sec2.methodOne();
}

然后在@Test JUnit 方法中将被执行所以你不会得到NPE。

【讨论】:

  • 添加但仍然给我 NullPointerException
  • 你能分享错误信息吗?我的意思是完整的堆栈跟踪?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-30
  • 2020-09-19
  • 2015-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多