fge
fge

Reputation: 121790

Test-NG: turning a @BeforeClass into something else (@BeforeSuite maybe?)

For a project of mine, I need two properties to be set at the JVM level before running tests (with testng, as the subject says). Here is the code I use to enforce the presence of these two properties:

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

This code has the problem that all my tests must inherit this class, therefore setUp() is run each time. How can I make this method run only once?

Upvotes: 3

Views: 318

Answers (2)

Cedric Beust
Cedric Beust

Reputation: 15608

Why not use a @BeforeSuite?

.

Upvotes: 1

oers
oers

Reputation: 18704

If all your tests extend this class, you could just put this into a static initializer. This will only be executed once (when the class is loaded).

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

Or put it in a completely different class, that is used/called by classes that need the password/user. You won't need to extend the AbstractPamTest then. Additionally you should provide getters/setter there, so that you can change user/password at runtime, if one testcase needs different values.

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

Upvotes: 2

Related Questions