gpt4 book ai didi

java - 我们如何在单元测试用例中写两个@beforeTest 方法?

转载 作者:行者123 更新时间:2023-11-29 06:13:10 24 4
gpt4 key购买 nike

我的测试用例中有两种方法。我想为我的每个测试方法使用两种不同的 @BeforeTest@BeforeMethod 方法。

我在我的单元测试类中写了两个 @BeforeMethod 方法,但这两个方法都会在每次单元测试方法执行时执行。

那么我们如何声明@BeforeMethod 方法来单独执行特定的测试方法呢?

我的单元测试类看起来像:

public class MyUnitTest{

String userName = null;
String password = null;

// Method 1
@Parameters({"userName"})
@BeforeMethod
public void beforeMethod1(String userName){
userName = userName;
}

@Parameters({"userName"})
@Test
public void unitTest1(String userNameTest){
System.out.println("userName ="+userName);
}


// Method 2
@Parameters({"userName","password"})
@BeforeMethod
public void beforeMethod2(String userName,String password){
this.userName = userName;
this.password = password;
}

@Parameters({"userName","password"})
@Test
public void unitTest2(String userNameTest,String passwordTest){
System.out.println("userName ="+this.userName+" \t Password ="+this.password);
}

}

有没有办法让:

  1. beforeMethod1 方法只为 unitTest1() 方法执行?
  2. beforeMethod2 方法只为 unitTest2() 方法执行?

最佳答案

你有几个选择:

  • 您可以使用 Method 参数声明 @BeforeMethod,检查该方法的名称,如果是 unitTest1,则调用 beforeMethod1(),如果是 unitTest2,则调用 beforeMethod2()。这可能不是我的第一选择,因为如果您更改方法的名称,它会有点脆弱。

  • 将这些方法和它们的 before 方法放在单独的类中,可能共享一个公共(public)父类(super class)。

关于java - 我们如何在单元测试用例中写两个@beforeTest 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6061366/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com