so cal cheesehead
so cal cheesehead

Reputation: 2573

How to instantiate objects and pass to methods using testng

I'm having a hell of a time trying to get objects correctly instantiated passed in to the other methods. Here's my code:

public class CreateAndDeleteCollector {

private static WebDriver driver = new FirefoxDriver();
private LoginPage login;
private AdminRtcpCollectorPage rtcp;
private AdminFunctions admin;

//DesiredCapabilities capability = DesiredCapabilities.firefox();
//String hubUrl = "http://localhost:4444/wd/hub";
//WebDriver d = new RemoteWebDriver(new URL(hubUrl), capability);


@BeforeMethod
public void setup() throws Exception {
    LoginPage login = new LoginPage(driver);
    AdminRtcpCollectorPage rtcp = new AdminRtcpCollectorPage(driver);
    AdminFunctions admin = new AdminFunctions();
}

@Test
public void newCollector() throws Exception {
    login.login("192.168.1.100", "admin", "admin");
    rtcp.goToRtcpCollectorPage();
    rtcp.newRtcpCollector("test-1", "test", "test", "192.168.1.100");
}

@Test(dependsOnMethods = { "newCollector" })
public void deleteCollector() throws Exception {
    admin.initialize(driver);
    rtcp.goToRtcpCollectorPage();
    admin.delete("test-1");
}

@AfterTest
public void logoutAndClose() {
    Util.logout(driver);
    driver.close();
}
}     

When I run this using TestNG as soon as I get to the first test method it errors with a NullPointerException because the login, rtcp, and admin. I'm sure I'm misunderstanding what the @BeforeMethod annotation is supposed to do.

I could put all my declarations and instantiate outside of a setup method, which works great by the way, however the reason for putting them in a method is because when I comment in the RemoteWebDriver line I get a "Default constructor cannot handle exception type..." error.

Does anyone have any suggestions?

I think using TestNG's factory and dataprovider may be an answer but I'm not sure how to apply it to my situation.

Upvotes: 0

Views: 929

Answers (1)

niharika_neo
niharika_neo

Reputation: 8531

You are getting a null pointer exception because you are redeclaring the variables in your method. Just remove "Loginpage" from

Loginpage login = ...

Use login =...

Upvotes: 2

Related Questions