Volk Volk - 2 months ago 7
C# Question

How to make a button start a new selenium unit test in MVC?

My question is as the title states; how do I make a button start a new selenium unit test in MVC? I'm new to MVC concepts and I wanted to learn to implement how to start a test via a button press in a web page to start a new selenium test. The Selenium test for now is on the users computer but eventually I want to make it start up on a virtual machine. I am using only one controller for now "Home" and am trying all of this on only one page for now "Index".

I've been able to make it do the selenium task on page load using the following code inside of Index.cshtml:

<p> Testing: @SeleniumController.OpenBrowser()</p>


And then inside of my HomeController.cs I have the following code (I know it's not a good practice to call pieces directly from the controller but i'm un-sure how do it any other way) :

public static string OpenBrowser()
{
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("http://www.google.com");

return driver.Title;
}


I also have a button that I haven't been able to figure out how to run the command with. I am not familiar with Javascript, I have been learning here and there but i'm still pretty far out for this.

Here is what my button code looks like:

<a class="btn btn-success" id="StartChrome">Start Chrome in Selenium &raquo;</a>


I have tried changing it instead of an "a" to type "input" or even "Submit" but that didn't get me very far unfortunately either.

I have been searching around for this answer for a few days (not necessarily running selenium but more just running actions on a button click event).

Any help with this would be very highly appreciated,
- Volk

Answer

I got it working my self with the following AJAX code.

    $("#btn1").click(function () {
    $.ajax({
        url: "/Home/RandNumber",
        datatype: "text",
        type: "POST",
        success: function (data) {
            $('#testarea').html(data);
        },
        error: function () {
            $("#testarea").html("ERROR");
        }
    });
});

And in the controller function was:

[HttpPost]
    public string RandNumber()
    {
        Random rand = new Random();
        return rand.Next(0, 100).ToString();
    }

With the Index.cshtml having this code:

<input id="btn1" type="button" class="btn btn-success" value="Load Random number &raquo;"/>

I changed out the randNumber to my selenium code and it worked.

Comments