将WatiN附加到IE的问题
Posted
技术标签:
【中文标题】将WatiN附加到IE的问题【英文标题】:Problem attaching WatiN to IE 【发布时间】:2010-11-19 17:02:19 【问题描述】:我正在尝试使用 WatiN 进行 UI 测试,我可以让测试正常工作,但之后我无法让 IE 关闭。
我正在尝试在我的班级清理代码中关闭 IE,使用 WatiN 的示例 IEStaticInstanceHelper technique。
问题似乎是附加到IE线程,超时:
_instance = IE.AttachTo<IE>(Find.By("hwnd", _ieHwnd));
(_ieHwnd 是 IE 首次启动时存储的 IE 句柄。)
这给出了错误:
类清理方法 Class1.MyClassCleanup 失败。错误 信息: WatiN.Core.Exceptions.BrowserNotFoundException: 找不到匹配的 IE 窗口 约束:属性“hwnd”等于 '1576084'。搜索在“30”后过期 秒..堆栈跟踪:在 WatiN.Core.Native.InternetExplorer.AttachToIeHelper.Find(约束 findBy,Int32 超时,布尔值 等待完成)
我确定我一定遗漏了一些明显的东西,有人对此有任何想法吗? 谢谢
为了完整起见,静态助手看起来像这样:
public class StaticBrowser
private IE _instance;
private int _ieThread;
private string _ieHwnd;
public IE Instance
get
var currentThreadId = GetCurrentThreadId();
if (currentThreadId != _ieThread)
_instance = IE.AttachTo<IE>(Find.By("hwnd", _ieHwnd));
_ieThread = currentThreadId;
return _instance;
set
_instance = value;
_ieHwnd = _instance.hWnd.ToString();
_ieThread = GetCurrentThreadId();
private int GetCurrentThreadId()
return Thread.CurrentThread.GetHashCode();
清理代码如下所示:
private static StaticBrowser _staticBrowser;
[ClassCleanup]
public static void MyClassCleanup()
_staticBrowser.Instance.Close();
_staticBrowser = null;
【问题讨论】:
【参考方案1】:问题在于,当 MSTEST 执行带有 [ClassCleanup]
属性的方法时,它将在不属于 STA 的线程上运行。
如果您运行以下代码,它应该可以工作:
[ClassCleanup]
public static void MyClassCleanup()
var thread = new Thread(() =>
_staticBrowser.Instance.Close();
_staticBrowser = null;
);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
WatiN 网站简要提到 WatiN 不能与不在 STA here 中的线程一起使用,但 [TestMethod]
在 STA 中运行并不明显,而像 [ClassCleanup]
和 [AssemblyCleanupAttribute]
这样的方法可以不是。
【讨论】:
【参考方案2】:默认情况下,当 IE 对象被销毁时,它们会自动关闭浏览器。
您的清理代码可能会尝试查找已关闭的浏览器,这就是您出错的原因。
【讨论】:
感谢您的回答,但不幸的是我的问题是浏览器保持打开状态【参考方案3】:通过转储 mstest 并改用 mbunit 自己解决了这个问题。我还发现我也不需要使用任何 IEStaticInstanceHelper 的东西,它就可以工作。
【讨论】:
我遇到了同样的问题,但我既没有使用 MSTest 也没有使用 MbUnit。您的环境中是否有任何其他可能解决此问题的变化? 我认为这取决于测试执行线程的方式,这描述了各种设置; watin.sourceforge.net/apartmentstateinfo.html 我设置它的方式是通过 FixtureSetUp 导航到执行操作等页面,然后在 FixtureTearDown 中关闭浏览器。 WatiN 在其他配置中表现不佳。以上是关于将WatiN附加到IE的问题的主要内容,如果未能解决你的问题,请参考以下文章
在 ajax 发布之后,附加的 div 不在 IE 8 中显示
如何使用 IE/.Net/C# 进行真正的多线程 Web 挖掘?