gpt4 book ai didi

java - 测试 NG : turning a @BeforeClass into something else (@BeforeSuite maybe? )

转载 作者:塔克拉玛干 更新时间:2023-11-02 18:59:45 25 4
gpt4 key购买 nike

对于我的一个项目,我需要在运行测试之前在 JVM 级别设置两个属性(如主题所述,使用 testng)。下面是我用来强制执行这两个属性的代码:

import org.testng.annotations.BeforeClass;

public class AbstractPamTest
{
protected String user;
protected String passwd;
protected String badPasswd;

@BeforeClass
public void setUp()
{
user = System.getProperty("test.login");
passwd = System.getProperty("test.passwd");
if (user == null || passwd == null)
throw new IllegalStateException("Please define test.login and"
+ " test.passwd before running tests");
badPasswd = passwd + "x";
}
}

这段代码有一个问题,我所有的测试都必须继承这个类,因此每次都运行setUp()。如何让这个方法只运行一次?

最佳答案

如果你所有的测试都扩展了这个类,你可以把它放到一个静态初始化器中。这只会执行一次(加载类时)。

public class AbstractPamTest
{
protected static final String user;
protected static final String passwd;
protected static final String badPasswd;

static
{
user = System.getProperty("test.login");
passwd = System.getProperty("test.passwd");
if (user == null || passwd == null)
throw new IllegalStateException("Please define test.login and"
+ " test.passwd before running tests");
badPasswd = passwd + "x";
}
}

或者将它放在一个完全不同的类中,由需要密码/用户的类使用/调用。那时您不需要扩展 AbstractPamTest。此外,您应该在那里提供 getters/setter,以便您可以在运行时更改用户/密码,如果一个测试用例需要不同的值。

  private  static String user;
private static String passwd;
private static String badPasswd;

static
{
user = System.getProperty("test.login");
passwd = System.getProperty("test.passwd");
if (user == null || passwd == null)
throw new IllegalStateException("Please define test.login and"
+ " test.passwd before running tests");
badPasswd = passwd + "x";
}

public static String getUser()
{
return user;
}

public static void setUser(String pUser)
{
user = pUser;
}

public static String getPasswd()
{
return passwd;
}

public static void setPasswd(String pPasswd)
{
passwd = pPasswd;
}

关于java - 测试 NG : turning a @BeforeClass into something else (@BeforeSuite maybe? ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8531950/

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