NUnit Playwright - Multiple inheritance BaseTests and PageTest

376 views Asked by At

How to achieve the equivalent of multiple inheriting from a custom BaseTests class and Playwright's PageTest class?

Problem

I have 2 types of tests in my application: Non-playwright and Playwright-ones.

Both types share common SetUp code found in BaseTests and should inherit from BaseTests.

However, Playwright tests should also inherit from Playwright's PageTest.

I've tried making Playwright tests inherit from both BaseTests and PageTest, but multiple inheritance is not possible in C# AFAIK.

Solutions tried

(1) To make BaseTests an interface instead of a class. However, I found that NUnit doesn't call BaseTests's SetUp in that case.

(2) To add an abstract class BasePageTests : PageTest and duplicate the code of BaseTests in it. Actually, I do already have a BasePageTests since there's more SetUp code specific to Playwright only. But I'd rather make it BasePageTests: BaseTests, PageTest not duplicate the code of BaseTests's SetUp in BasePageTests.

Code

abstract class BaseTests {
  protected virtual CustomWebApplicationFactoryOptions? ConfigureCustomWebApplicationFactoryOptions() => null;

  [SetUp]
  public void BaseTestsSetUp() {
    // Lots of set-up code. E.g., cleaning up the database.
  }
}

class SampleNonPlaywrightTest : BaseTests {
  // ...
}

// `BasePageTests` needs `BaseTests`'s SetUp, but also has its own SetUp code.
// Needs to inherit from Playwright's `PageTest` (or make its children inherit from `PageTest`), but multiple inheritance is not possible!
abstract class BasePageTests : BaseTests, PageTest {
    protected override CustomWebApplicationFactoryOptions? ConfigureCustomWebApplicationFactoryOptions() =>
        new() { StartRealServer = true, BypassAuth = true };

  [SetUp]
  public void BasePageTestsSetUp() {
    // More set-up relevant only to page tests. E.g., calling `_application.CreateClient()` to actually start the server
  }
}

class SamplePlaywrightTest : BasePageTests {
  // ...
}

So, in summary: What is the idiomatic way to achieve the above without code duplication?

1

There are 1 answers

0
Gaurav Khurana On

You can make BaseTest inherit PageTest, so that way your playwright test can use use is which inheirts from BaseTest which would inherit from PageTest

Child Class --> BaseTest --> PageTest

Also in case you are using PageObjects then your Page Objects can directly inherit from PageTest without the need of base class

and your TestClasses can go via BaseTest --> PageTest