如何实现相当于多重继承自定义的
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 {
// ...
}
那么,总而言之:在不重复代码的情况下实现上述目标的惯用方法是什么?
你可以让BaseTest继承PageTest,这样你的剧作家测试就可以使用继承自BaseTest的继承自PageTest的
子类 --> BaseTest --> PageTest
如果您使用PageObjects,那么您的页面对象可以直接从PageTest继承,而不需要基类
你的测试类可以通过 BaseTest --> PageTest