You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何开发桌面应用触发MSTest框架下的Selenium自动化测试?

用WPF开发MSTest自动化测试触发工具方案

完全可以用WPF开发这款桌面应用,结合你已经掌握的dotnet test命令,以下是具体实现步骤:

一、创建WPF项目

直接在Visual Studio里新建WPF应用项目,根据你的测试项目框架版本,选择.NET Framework或.NET 6+/Core即可。

二、设计UI界面

根据需求设计包含参数输入和执行反馈的界面,核心控件参考:

  • 测试DLL路径输入框(带浏览按钮)
  • 测试筛选条件输入框(对应dotnet test的--filter参数,可指定测试方法/类别)
  • 自定义测试参数区(如Selenium目标浏览器、测试环境地址)
  • 执行按钮
  • 实时日志输出框(只读)

示例XAML片段:

<Grid Margin="20">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <StackPanel Grid.Row="0" Orientation="Horizontal" Margin="0 0 0 10">
        <Label Content="测试DLL路径:" Width="100"/>
        <TextBox x:Name="TxtTestDllPath" Width="300"/>
        <Button Content="浏览" Click="BtnBrowse_Click" Margin="10 0"/>
    </StackPanel>
    <StackPanel Grid.Row="1" Orientation="Horizontal" Margin="0 0 0 10">
        <Label Content="测试筛选条件:" Width="100"/>
        <TextBox x:Name="TxtFilter" Width="300" Hint="示例: FullyQualifiedName~Namespace.TestClass.TestMethod"/>
    </StackPanel>
    <StackPanel Grid.Row="2" Orientation="Horizontal" Margin="0 0 0 10">
        <Label Content="目标浏览器:" Width="100"/>
        <ComboBox x:Name="CmbBrowser" Width="150">
            <ComboBoxItem Content="Chrome"/>
            <ComboBoxItem Content="Firefox"/>
        </ComboBox>
        <Label Content="测试环境地址:" Width="120" Margin="10 0"/>
        <TextBox x:Name="TxtEnvUrl" Width="200"/>
    </StackPanel>
    <TextBox Grid.Row="3" x:Name="TxtLog" IsReadOnly="True" VerticalScrollBarVisibility="Auto" Margin="0 10 0 10"/>
    <Button Grid.Row="4" Content="执行测试" Click="BtnRunTest_Click" Width="100" HorizontalAlignment="Right"/>
</Grid>

三、编写后台执行逻辑

核心是通过System.Diagnostics.Process调用dotnet test命令,传递用户输入的参数并捕获输出日志。

1. 浏览按钮逻辑(选择测试DLL)

private void BtnBrowse_Click(object sender, RoutedEventArgs e)
{
    var openFileDialog = new OpenFileDialog();
    openFileDialog.Filter = "测试DLL|*.dll";
    if (openFileDialog.ShowDialog() == true)
    {
        TxtTestDllPath.Text = openFileDialog.FileName;
    }
}

2. 执行测试按钮核心逻辑

private async void BtnRunTest_Click(object sender, RoutedEventArgs e)
{
    if (string.IsNullOrEmpty(TxtTestDllPath.Text))
    {
        AppendLog("请选择测试DLL路径");
        return;
    }

    BtnRunTest.IsEnabled = false;
    TxtLog.Clear();
    AppendLog("开始执行测试...");

    // 构建dotnet test命令参数
    var args = new List<string>
    {
        "test",
        TxtTestDllPath.Text
    };

    // 添加筛选条件
    if (!string.IsNullOrEmpty(TxtFilter.Text))
    {
        args.Add($"--filter {TxtFilter.Text}");
    }

    // 添加自定义测试参数(传递给MSTest)
    var browser = (CmbBrowser.SelectedItem as ComboBoxItem)?.Content.ToString();
    var envUrl = TxtEnvUrl.Text;
    if (!string.IsNullOrEmpty(browser))
    {
        args.Add($"-- RunConfiguration.TestRunParameters.Parameter(name=\"Browser\", value=\"{browser}\")");
    }
    if (!string.IsNullOrEmpty(envUrl))
    {
        args.Add($"-- RunConfiguration.TestRunParameters.Parameter(name=\"EnvUrl\", value=\"{envUrl}\")");
    }

    // 配置进程启动信息
    var processStartInfo = new ProcessStartInfo
    {
        FileName = "dotnet",
        Arguments = string.Join(" ", args),
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        UseShellExecute = false,
        CreateNoWindow = true,
        WorkingDirectory = Path.GetDirectoryName(TxtTestDllPath.Text)
    };

    // 启动进程并捕获输出
    using var process = new Process { StartInfo = processStartInfo };
    process.OutputDataReceived += (s, ev) => { if (!string.IsNullOrEmpty(ev.Data)) AppendLog(ev.Data); };
    process.ErrorDataReceived += (s, ev) => { if (!string.IsNullOrEmpty(ev.Data)) AppendLog($"错误: {ev.Data}"); };

    process.Start();
    process.BeginOutputReadLine();
    process.BeginErrorReadLine();

    await Task.Run(() => process.WaitForExit());

    AppendLog($"测试执行完成,退出码: {process.ExitCode}");
    BtnRunTest.IsEnabled = true;
}

// 日志追加方法(确保在UI线程更新)
private void AppendLog(string message)
{
    Application.Current.Dispatcher.Invoke(() =>
    {
        TxtLog.AppendText($"{DateTime.Now:HH:mm:ss} - {message}\r\n");
        TxtLog.ScrollToEnd();
    });
}

四、在MSTest项目中接收自定义参数

在测试类中通过TestContext获取WPF传递的参数,用于初始化Selenium Driver:

[TestClass]
public class SeleniumTests
{
    public TestContext TestContext { get; set; }
    private IWebDriver _driver;

    [TestInitialize]
    public void Setup()
    {
        var browser = TestContext.Properties["Browser"]?.ToString() ?? "Chrome";
        var envUrl = TestContext.Properties["EnvUrl"]?.ToString() ?? "https://default-env.com";

        // 根据选择的浏览器初始化Driver
        switch (browser.ToLower())
        {
            case "chrome":
                _driver = new ChromeDriver();
                break;
            case "firefox":
                _driver = new FirefoxDriver();
                break;
            // 可扩展其他浏览器配置
        }

        _driver.Navigate().GoToUrl(envUrl);
    }

    [TestCleanup]
    public void Teardown()
    {
        _driver?.Quit();
    }

    [TestMethod]
    public void SampleTest()
    {
        // 你的Selenium测试逻辑
    }
}

注意事项

  • 确保WPF应用和测试项目的.NET版本兼容,避免运行时错误
  • 测试DLL所在目录需包含Selenium Driver等依赖文件,可在WPF中添加依赖复制逻辑
  • 长时间运行的测试用异步方式执行,避免界面卡顿
  • 可扩展参数项,比如添加测试结果报告路径(对应dotnet test的--results-directory参数)

内容的提问来源于stack exchange,提问作者Doraemon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 11:17:49