NUnit Playwright - 多重继承 BaseTests 和 PageTest

问题描述 投票:0回答:1

如何实现相当于多重继承自定义的

BaseTests
类和Playwright的
PageTest
类?

问题

我的应用程序中有两种类型的测试:非剧作家测试和剧作家测试。

这两种类型共享在

SetUp
中找到的通用
BaseTests
代码,并且应该继承自
BaseTests

但是,Playwright 测试也应该继承 Playwright 的

PageTest

我尝试让 Playwright 测试同时继承

BaseTests
PageTest
,但多重继承在 C# AFAIK 中是不可能的。

尝试过的解决方案

(1) 使

BaseTests
成为接口而不是类。但是,我发现在这种情况下 NUnit 不会调用
BaseTests
SetUp

(2) 添加

abstract class BasePageTests : PageTest
,并复制其中
BaseTests
的代码。实际上,我已经有了一个
BasePageTests
,因为还有更多
SetUp
代码仅针对剧作家。但我宁愿让它
BasePageTests: BaseTests, PageTest
不重复
BaseTests
SetUp
的代码
BasePageTests

代码

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 {
  // ...
}

那么,总而言之:在不重复代码的情况下实现上述目标的惯用方法是什么?

c# .net .net-core nunit playwright-dotnet
1个回答
0
投票

你可以让BaseTest继承PageTest,这样你的剧作家测试就可以使用继承自BaseTest的继承自PageTest的

子类 --> BaseTest --> PageTest

如果您使用PageObjects,那么您的页面对象可以直接从PageTest继承,而不需要基类

你的测试类可以通过 BaseTest --> PageTest

© www.soinside.com 2019 - 2024. All rights reserved.