如果我需要在 Selenium C# 测试运行时检查网络请求的情况,该怎么做?
与大家分享我的解决方案。
我开发了一个很好的解决方案来捕获网络请求。它适用于当前最新版本的 Selenium Webdriver 2.33.0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
namespace MyNameSpace
{
public class BrowserNetworkMonitoringTool
{
private readonly NetworkManager manager;
public List<NetworkRequestSentEventArgs> Requests;
public List<NetworkResponseReceivedEventArgs> Responses;
public BrowserNetworkMonitoringTool(IWebDriver driver)
{
manager = new NetworkManager(driver);
Requests = new List<NetworkRequestSentEventArgs>();
Responses = new List<NetworkResponseReceivedEventArgs>();
}
public void StartMonitoring()
{
manager.NetworkResponseReceived += ResponseReceivedHandler;
manager.NetworkRequestSent += ManagerOnNetworkRequestSent;
var monitor = manager.StartMonitoring();
monitor.Wait();
}
private void ManagerOnNetworkRequestSent(object sender, NetworkRequestSentEventArgs e)
{
Requests.Add(e);
}
private void ResponseReceivedHandler(object sender, NetworkResponseReceivedEventArgs e)
{
Responses.Add(e);
}
public void StopMonitoring()
{
manager.StopMonitoring();
}
public void Clear()
{
Requests.Clear();
Responses.Clear();
}
}
}
使用示例:
BrowserNetworkMonitoringTool networkMonitoringTool = new BrowserNetworkMonitoringTool(CurrentDriver);
networkMonitoringTool.StartMonitoring();
//Do any actions you need to do in your test here
networkMonitoringTool.StopMonitoring();
var allResponses = networkMonitoringTool.Responses;
foreach (var response in allResponses)
{
var unexpectedErrors = new List<string>();
if (response.ResponseStatusCode > 302)
{
unexpectedErrors.Add($"Response: {response.ResponseUrl} has response code: {response.ResponseStatusCode}");
}
if (unexpectedErrors.Any())
{
Assert.Fail($"Unexpected errors found: {string.Join(", ", unexpectedErrors)}");
}
}