My Playwright test is in a Junit5 tests. What I am trying to achieve is that, if there is any assertion on my test (basically if the test fails), save the .har file, otherwise discard it.
@Test
public void myTest() {
try {
//.har file already recording
navigateToSomePages();
assertThat(page.locator(cssSelector)).hasText("allGood");
} catch (AssertionFailedError | TimeoutError error) {
// regardless of the test outcome the .har file is kept. Just wanted it in case of fail/assertion is throw.
doScreenShot();
throw error;
}
}
@BeforeEach
// before each test start the HAR recording
protected void beforeEachAbstractMethod() {
context = browser.newContext(new Browser.NewContextOptions()
.setRecordHarPath(Paths.get("file.har"))
.setRecordHarMode(HarMode.MINIMAL));
}
Can't really find anything related to stopping the HAR file generation, once started: https://playwright.dev/java/docs/mock#recording-a-har-file.
One thing that might work is to invoke File.delete() every time after assertThat(...), but that is really ugly :(
Maybe you could use the
TestWatcher
function in JUnit5 (from 5.7)Documentation is here
You'll then be able to implement a testSuccessful method that will always be called when test passed, in order to delete the file generated earlier. By doing so, your file won't get deleted if test is disabled, failed or aborted (since each has it's own method
testDisabled
,testFailed
ortestAborted
)