Skip to content

Commit

Permalink
docs(test-runners-java.md): added testng implementation (microsoft#26537
Browse files Browse the repository at this point in the history
  • Loading branch information
Tahanima authored and Germandrummer92 committed Oct 27, 2023
1 parent c0c3cb9 commit ca6052f
Showing 1 changed file with 74 additions and 0 deletions.
74 changes: 74 additions & 0 deletions docs/src/test-runners-java.md
Original file line number Diff line number Diff line change
Expand Up @@ -278,3 +278,77 @@ Also, Playwright command line tools can be run with :
```bash
./gradlew playwright --args="help"
```

## TestNG

In [TestNG](https://testng.org/) you can initialize [Playwright] and [Browser] in [@BeforeClass](https://javadoc.io/doc/org.testng/testng/latest/org/testng/annotations/BeforeClass.html) method and
destroy them in [@AfterClass](https://javadoc.io/doc/org.testng/testng/latest/org/testng/annotations/AfterClass.html). In the example below all three test methods use the same
[Browser]. Each test uses its own [BrowserContext] and [Page].

```java
package org.example;

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import org.testng.annotations.*;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

public class TestExample {
// Shared between all tests in this class.
Playwright playwright;
Browser browser;

// New instance for each test method.
BrowserContext context;
Page page;

@BeforeClass
void launchBrowser() {
playwright = Playwright.create();
browser = playwright.chromium().launch();
}

@AfterClass
void closeBrowser() {
playwright.close();
}

@BeforeMethod
void createContextAndPage() {
context = browser.newContext();
page = context.newPage();
}

@AfterMethod
void closeContext() {
context.close();
}

@Test
void shouldClickButton() {
page.navigate("data:text/html,<script>var result;</script><button onclick='result=\"Clicked\"'>Go</button>");
page.locator("button").click();
assertEquals("Clicked", page.evaluate("result"));
}

@Test
void shouldCheckTheBox() {
page.setContent("<input id='checkbox' type='checkbox'></input>");
page.locator("input").check();
assertTrue((Boolean) page.evaluate("() => window['checkbox'].checked"));
}

@Test
void shouldSearchWiki() {
page.navigate("https://www.wikipedia.org/");
page.locator("input[name=\"search\"]").click();
page.locator("input[name=\"search\"]").fill("playwright");
page.locator("input[name=\"search\"]").press("Enter");
assertEquals("https://en.wikipedia.org/wiki/Playwright", page.url());
}
}
```

0 comments on commit ca6052f

Please sign in to comment.