0

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?

Hossam El-Deen
  • 972
  • 1
  • 13
  • 27
  • What's ```PageTest```? C# can't inherit two class I think you know that and you can try to extract the code in the ```Setup``` to a new class so you don't need to write them two times but still need to ```invoke``` them in two ```setup``` – MichaelMao Jan 04 '23 at 09:47
  • `PageTest` is a class in Playwright that all test classes must inherit from (AFAIK). Yes, I can do that. One possible complication, though: In `BaseTests` I also have some members variables that I initialize in `SetUp`. E.g., a `DbContext`, an `IMapper`, a Scope, .. etc. Defining them in each test class is a bit duplicate-y. Perhaps if I have the method you talk about and its interface is `X(out DBContext, out IMapper, .. etc.)`, that'd make it easier to propagate any new members to all test classes. – Hossam El-Deen Jan 06 '23 at 00:32

0 Answers0