我正在尝试使用 Watin 测试 asp:DropDownList,但是当我尝试从呈现的 SelectList 中选择一个选项时,它会抛出 System.FormatException:字符串未被识别为有效的 bool 值。
我的页面代码是:
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="TesteSelect._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:DropDownList ID="ddl"
Width="75px" runat="server">
<asp:ListItem Text="Yes" Value="true" Selected="true"></asp:ListItem>
<asp:ListItem Text="No" Value="false"></asp:ListItem>
</asp:DropDownList>
</asp:Content>
我的测试是:
using NUnit.Framework;
using WatiN.Core;
namespace Test
{
[TestFixture]
public class ATest
{
[Test]
public void Should_be_able_to_select_yes_from_ddl()
{
using( var browser = new IE())
{
browser.GoTo(Properties.Settings.Default.ServerAddress + "Default.aspx");
SelectList ddl = browser.SelectList(Find.ById("MainContent_ddl"));
ddl.Option("Yes").Select();
Assert.That(ddl.SelectedItem.Equals("Yes"));
}
}
[Test]
public void Should_be_able_to_select_no_from_ddl()
{
using (var browser = new IE())
{
browser.GoTo(Properties.Settings.Default.ServerAddress + "Default.aspx");
SelectList ddl = browser.SelectList(Find.ById("MainContent_ddl"));
ddl.Option("No").Select();
Assert.That(ddl.SelectedItem.Equals("No"));
}
}
}
}
“否”测试顺利通过,但"is"测试因该异常和此堆栈跟踪而失败:
ATest.Should_be_able_to_select_yes_from_ddl : FailedSystem.FormatException : String was not recognized as a valid Boolean. at System.Boolean.Parse(String value) at WatiN.Core.Option.setSelected(Boolean value, Boolean WaitForComplete) at WatiN.Core.Option.Select() at Test.ATest.Should_be_able_to_select_yes_from_ddl() in ATest.cs: line 16
查看此处提供的源代码 => http://watin.svn.sourceforge.net/viewvc/watin/trunk/src/Core/Option.cs?revision=1194&view=markup
我可以看到错误发生在第 136 行的这段代码段中:
...
134 private void setSelected(bool value, bool WaitForComplete)
135 {
136 if (bool.Parse(GetAttributeValue("selected")) == value) return;
137
138 SetAttributeValue("selected", value.ToString().ToLowerInvariant());
139 if (WaitForComplete)
140 {
141 ParentSelectList.FireEvent("onchange");
142 }
143 else
144 {
145 ParentSelectList.FireEventNoWait("onchange");
146 }
147 }
当我查看生成的 HTML 时,这是有道理的,因为这就是呈现的内容:
<select name="ctl00$MainContent$ddl" id="MainContent_ddl" style="width:75px;">
<option selected="selected" value="true">Yes</option>
<option value="false">No</option>
</select>
因此它无法将“selected”解析为 bool 值,这是有道理的。我该如何度过这个难关?
最佳答案
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:DropDownList ID="ddl" Width="75px" runat="server">
<asp:ListItem Text="Yes" Value="1" Selected="true"></asp:ListItem>
<asp:ListItem Text="No" Value="0"></asp:ListItem>
</asp:DropDownList>
试试这个,让我知道会发生什么。
关于asp.net - 使用 Watin 选择 Asp.Net DropDownList 值会引发 System.FormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5581689/