我正在设计一个测试应用程序(使用 NUnit),它必须在网页中导航(通过 Selenium Webdriver API)。我想使用枚举对站点结构进行建模,以便能够通过此枚举告诉方法导航到哪里(尤其是 NUnit 方法)。
this.NavigateTo(Page.HomePage);
这是一个强烈的要求(在某处有一个枚举类型)主要是因为 NUnit 不能传递非原始类型。例如,这种语法对于 NUnit 来说是不可能的,因为 Page 必须是原始的或枚举的:
static class Page{
public static Page HomePage;
public static Page UserAccountPage;
}
/* ... later ... */
[TestCase(Page.HomePage)]
void TestMethod(Page p) { ...
我也想使用相同的枚举来进行基本继承,比如
interface IPage{}
interface IPageNavigatable : Page {}
interface IPageUserRelated : Page {}
interface IWildcardPage : Page {}
enum Page{
HomePage : IPageNavigatable,
UserAccountPage : IPageNavigatable IPageUserRelated,
ErrorPage : /* none */,
AnyPage : IWildcardPage
}
然后,我将能够制作非常有趣的方法,例如
bool IsCurrentPage(IWildcardPage p);
void LoginThenNavigate(String user, String pw, IPageUserRelated p);
Page WhereAmI(); /* and use this value with IsAssignableFrom */
我知道 C# 禁止枚举继承(我仍然不明白这个选择,但这不是我现在的问题)并且我已经阅读了一些变通方法,包括一个从头开始重新编码的类枚举机制;没有一个看起来令人满意。
我最好的想法是使用一个带有内部枚举和一些公共(public) bool 值的复杂类。不是很满意...
public class Page{
enum Pages { /* you know them */}
public Page.Pages InnerPage;
public bool isWildcard, isUserRelated, ...;
public Page(Page.Pages p){
this.InnerPage = p;
switch (p){
case ...:
case ...:
this.isWildcard = true;
break;
/* ... */
}
}
}
/* NUnit calls */
[TestCase(Page.Pages.HomePage)]
void TestMethod(Page.Pages p) { ...
此外,在一个完美的世界中,我喜欢将我的枚举类型值与字符串或 URI“链接”起来,这样我就可以编写如下内容:
enum Page{
HomePage : IPageNavigatable = "/index.php",
UserAccountPage : IPageNavigatable IPageUserRelated = "/user.php",
ErrorPage : /* none */ = (String) null,
AnyPage : IWildcardPage = (String) null
}
/* ... */
Page p;
Selenium.Webdriver drv;
drv.Navigate().GoToUrl(new Url(p.ToString()));
这对我来说是个棘手的问题。谁能帮忙?
编辑:正如 Chris 在下面指出的那样,一个线索是 NUnit(通过属性)可以采用 Object 类型的参数。使用它,可能有一种方法可以用我的继承结构实现几乎没有代码的对象,并重新编码枚举机制的一部分(并链接到 URL 字符串)。
这不是我梦想的解决方案,但可能会奏效......
请您参考如下方法:
您确定它们一定是原语(顺便说一下,我们在 .net 世界中称这些值类型或结构)? This page似乎暗示您受到限制的原因是 .NET 属性的固有限制,这又描述了 here :
Attribute parameters are restricted to constant values of the following types:
Simple types (bool, byte, char, short, int, long, float, and double)
string
System.Type
enums
object (The argument to an attribute parameter of type object must be a constant value of one of the above types.)
One-dimensional arrays of any of the above types
这向我表明以下方法可行:
static class Pages {
public const String HomePage = "Home Page";
public const String UserAccountPage = "User Account Page";
}
[TestCase(Pages.HomePage)]
void TestMethod(Page p) { ...
