Search code examples
winformstestingradio-button

How to check radio button automatically with third-party program


I'm making a web that provides multiple choice tests, but I'm too lazy to test it the human way. I want to write a simple C# .Net winform program that help me to check every A (or B, C, D) radio button of the question in the web browser. I wonder if a winform application could do that.

Thank for reading :)


Solution

  • From what I understand, your main goal isn't to write a C# winforms application, but simply to test your web form. Therefore, instead of spending time to create a dedicated C# application to test your website, I'd suggest you look into dedicated web testing solutions. There is a very similiar question here already: How apply Unit tests in ASP.NET webforms

    If you don't like that, then another option would be to generate test scripts for the FireFox iMacros extension. The syntax is fairly simple.

    Generally speaking, you should look into the topic of existing solutions for testing web forms. It is not advisable to create a dedicated solution simply for that purpose.


    EDIT:

    Ok, from your comment I see that it's important for you to have this solution in WinForms, therefore I'll rectify my answer. To do this in WinForms, perform the following steps:

    1. Use the WebBrowser class - add the relevant WebBrowser control to your winform.
    2. Add a button, you can call it "btnTest".
    3. Double-click this button in the editor, so a btnTest_Click(...) method stub is created.
    4. In code, set the desired browser address string like so: string address = @"D:\path\to\my\file.html" or use a http:// address instead if you want that.
    5. Navigate to this address using the WebBrowser.Navigate method, like so: webBrowser.Navigate(new Uri(address));

    This can all run in Form1's constructor after InitializeComponent(); or wherever else you want (on another button combined with an address textbox perhaps?). Now for your test button code. To perform tests you can use WebBrowser.Document's methods to get HtmlElements and perform actions on them. See the provided documentation links for details.

    Some examples:

    HtmlElement checkboxGenderFemale = webBrowser.Document.GetElementById("female");
    checkboxGenderFemale.InvokeMember("CLICK");
    

    This will simulate a click and check the given checkbox. Remember to assign IDs to all your elements. To fill out a text input, you can use this code snippet:

    HtmlElement nameInput = webBrowser.Document.GetElementById("firstname");
    nameInput.SetAttribute("value", "NewName");
    

    As you can see, you can simulate clicks and modify attributes of elements with ease. You can put those code examples in your btnTest_Click(...) method and see how it works. If you've done the navigation in Form1's constructor, the form should open with the page already loaded. After btnTest is clicked, the relevant test will be performed.