C# Selenium测试UI筛选功能实现及TestFixture测试分类标签设置咨询
Hey there! Let's tackle your problem step by step—you need two main things: a way to tag your Selenium tests with categories like Smoke/Regression/Integration, and a UI that can filter and run those tagged tests. Since you're using NUnit's TestFixture, we can leverage NUnit's built-in features plus a simple C# UI to make this work.
NUnit has a built-in [Category] attribute that’s perfect for grouping tests into your desired categories. You can apply it directly to individual test methods, or even to an entire TestFixture if all tests in that class belong to the same category.
Example Test Class with Categories
using NUnit.Framework; [TestFixture] public class SeleniumUITests { [Test] [Category("Smoke")] public void Test1_VerifyHomepageLoads() { // Your Selenium test logic here } [Test] [Category("Smoke")] public void Test2_VerifyLoginButtonExists() { // Your Selenium test logic here } [Test] [Category("Regression")] public void Test3_VerifyCheckoutFlow() { // Your Selenium test logic here } [Test] [Category("Integration")] public void Test4_VerifyAPICallIntegration() { // Your Selenium test logic here } // You can even apply multiple categories to a single test [Test] [Category("Smoke")] [Category("Regression")] public void Test5_VerifySearchFunctionality() { // Your Selenium test logic here } }
We’ll create a simple WinForms UI (WPF works similarly, same core logic) that scans your test assembly, loads categorized tests, lets you filter by category, and runs selected tests.
Step 1: UI Setup
First, add these components to your form:
- A
ComboBox(dropdown) for selecting categories (Smoke/Regression/Integration/All) - A
ListBoxto display filtered test cases - A
Buttonto trigger test execution
Step 2: Load Test Cases & Categories
We’ll use reflection to scan your test assembly and extract test methods along with their categories. For more robustness, you could use NUnit’s official engine API, but this simplified reflection approach works for most cases.
using System.Reflection; using NUnit.Framework; // Helper class to store test case details public class TestCaseDetails { public string TestName { get; set; } public List<string> Categories { get; set; } = new(); public MethodInfo TestMethod { get; set; } } private List<TestCaseDetails> _allTestCases; private void LoadTestCases() { _allTestCases = new List<TestCaseDetails>(); // Replace "YourTestAssemblyName" with the name of your test project's DLL var testAssembly = Assembly.Load("YourTestAssemblyName"); foreach (var type in testAssembly.GetTypes()) { // Only look at classes marked with TestFixture if (type.GetCustomAttribute<TestFixtureAttribute>() == null) continue; foreach (var method in type.GetMethods()) { // Only look at methods marked with Test if (method.GetCustomAttribute<TestAttribute>() == null) continue; var testDetails = new TestCaseDetails { TestName = method.Name, TestMethod = method }; // Extract all Category attributes from the test method var categoryAttributes = method.GetCustomAttributes<CategoryAttribute>(); foreach (var attr in categoryAttributes) { testDetails.Categories.Add(attr.Name); } // Add an "Uncategorized" tag if no categories are set if (!testDetails.Categories.Any()) { testDetails.Categories.Add("Uncategorized"); } _allTestCases.Add(testDetails); } } }
Step 3: Filter Tests by Selected Category
Hook up the dropdown’s selection change event to update the list of visible tests:
private void Form_Load(object sender, EventArgs e) { LoadTestCases(); // Populate dropdown with unique categories + "All" option var allCategories = _allTestCases .SelectMany(t => t.Categories) .Distinct() .ToList(); allCategories.Insert(0, "All"); comboBoxCategories.Items.AddRange(allCategories.ToArray()); comboBoxCategories.SelectedIndex = 0; // Default to "All" } private void comboBoxCategories_SelectedIndexChanged(object sender, EventArgs e) { var selectedCategory = comboBoxCategories.SelectedItem.ToString(); var filteredTests = selectedCategory == "All" ? _allTestCases : _allTestCases.Where(t => t.Categories.Contains(selectedCategory)).ToList(); // Update the list box with filtered tests listBoxTests.Items.Clear(); foreach (var test in filteredTests) { listBoxTests.Items.Add(test); } }
Step 4: Execute Selected Tests
Add click logic to the run button to execute the selected tests. Note: For production use, consider using NUnit’s NUnit.Engine package to run tests properly (with full test result reporting), but this simplified example works for demonstration:
private void btnRunTests_Click(object sender, EventArgs e) { foreach (TestCaseDetails test in listBoxTests.SelectedItems) { try { // Create an instance of the test class and run the method var testClassInstance = Activator.CreateInstance(test.TestMethod.DeclaringType); test.TestMethod.Invoke(testClassInstance, null); MessageBox.Show($"{test.TestName} passed!", "Success"); } catch (Exception ex) { // Show failure details (inner exception has the actual test error) var errorMessage = ex.InnerException?.Message ?? ex.Message; MessageBox.Show($"{test.TestName} failed:\n{errorMessage}", "Test Failure"); } } }
- Custom Categories: If you want more control than NUnit’s
[Category], create a custom attribute (e.g.,[TestCategory("Smoke")]) and modify the reflection logic to read it instead. - Parameterized Tests: Combine
[Category]with[TestCase]or[TestCaseSource]—they work seamlessly together. - Better Test Execution: Use NUnit’s
NUnit.EngineNuGet package to run tests in a proper test context, which gives you access to detailed results (like assertion failures, test duration, etc.).
内容的提问来源于stack exchange,提问作者Kramlessur

