Selenium+specflow Automated Test Day Practice (C #)

Source: Internet
Author: User

  a year ago in a chat with a great God to understand the selenium automated testing, excitedly bought "0 cost to achieve Web automation testing-based on selenium webdriver and Cucumber", looked at the previous chapters confused, by a variety of theories hit the wrong. Since then I think the automated test is very good, but far away, no unit test so easy to learn AH.

These two days, the site developed a big pit was dug out, almost the entire project to change all the pages. Plus the new features of pre-development in SVN a merger, looking at a lot of conflict, I completely did not end, thinking to test it again, but so many pages and business is a few days.

If all the tests were automated, it would be nice to expand the scene and business logic in the future. recalled the selenium, I just have to try and write a Web test.

First, Selenium

According to the online data, the first generation of selenium is mainly divided into RC version and IDE version. The latter can only be used on Firefox, which is available on any browser and supports a variety of languages. RC version seems to be what I want, a search on the internet, found that it is troublesome to use, and most of Java, there is server side and client side of the point, server side needs JDK compilation, the use of basic command line, in order to figure quickly had to abandon.

Later in the NuGet found the webdriver, in fact, is Selenium2.0, decisive outfit. In combination with some cases of webdriver on the Internet, we have successfully written a login Web authentication immediately.

The final NuGet package for my project is as follows:

The main installation webdriver should be available, the other is dependencies, can be automatically installed

The main reference here is http://blog.sina.com.cn/s/blog_5c9288aa0101de2u.html

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingOpenqa.selenium;usingnunit.framework;usingOpenQA.Selenium.Firefox;usingOpenQA.Selenium.Chrome;usingOpenQA.Selenium.Support.UI;namespaceconsoleapplication1{[Testfixture]classProgram {Static voidMain (string[] args) {Program P=NewProgram ();            P.setuptest ();            P.theuntitledtest ();        P.teardowntest (); }        PrivateIwebdriver driver; PrivateStringBuilder verificationerrors; Private stringBaseURL; Private BOOLAcceptnextalert =true; [SetUp] Public voidsetuptest () {driver=NewChromedriver (); BaseURL=""; Verificationerrors=NewStringBuilder (); } [TearDown] Public voidteardowntest () {Try{driver.            Quit (); }            Catch(Exception) {//Ignore Errors If unable to close the browser} assert.areequal ("", verificationerrors.tostring ()); } [Test] Public voidtheuntitledtest () {driver. Navigate ().            Gotourl (BaseURL); Driver. Findelement (By.id ("LoginName")).            Clear (); Driver. Findelement (By.id ("LoginName")). SendKeys (""); Driver. Findelement (By.id ("Password")).            Clear (); Driver. Findelement (By.id ("Password")). SendKeys (""); Driver. Findelement (By.id ("")).            Click (); webdriverwait wait=NewWebdriverwait (Driver, Timespan.fromseconds (Ten)); Wait. Until<BOOL> ((d) =            {                Try{iwebelement element= D.findelement (By.id ("")); Assert.AreEqual (element. Findelement (By.classname ("")). Text,""); return false; }                Catch(nosuchelementexception) {return true;        }            }); }        Private BOOLiselementpresent (by) {Try{driver.                Findelement (by); return true; }            Catch(nosuchelementexception) {return false; }        }        Private BOOLisalertpresent () {Try{driver. SwitchTo ().                Alert (); return true; }            Catch(noalertpresentexception) {return false; }        }        Private stringClosealertandgetitstext () {Try{ialert Alert=driver. SwitchTo ().                Alert (); stringAlerttext =alert.                Text; if(Acceptnextalert) {alert.                Accept (); }                Else{alert.                Dismiss (); }                returnAlerttext; }            finally{Acceptnextalert=true; }        }    }}
View Code

Run times wrong, can't find file chromedriver.exe, online Search, on the official web download good, put in the program running directory, you can run

The previous code needs to pay attention to a point, webdriverwait section is mainly to wait for the page to be refreshed, otherwise, no page jumps, start scratching elements or judgment, will certainly be wrong. Here the main use of the explicit waiting

Reference http://blog.csdn.net/aerchi/article/details/8055913

The test passes, but each test instance has to write this way again, and the workload is too great!

Such a huge test code would definitely need a framework for organizing it. Here is the turn of the Specflow.

Second, Specflow

Specflow is actually cucumber. NET version, found on the cucumber official website. Cucumber is an implementation of acceptance testing, almost like natural language, equivalent to the test of pure black box.

The syntax is what scenario (scenary), what are the prerequisites (Given), what actions are performed to get what results (then)

In addition to the NuGet package (see above), you also need to install the VS plugin to use

Specflow official website on the specific use of the method in fact there are simple cases, there are very detailed documentation. Of course, most of it is in English, I read the speed of the English is too slow, so temporarily use which to check.

The feature file that you added

Right-click inside the feature File editing window to generate the corresponding action

Here is a section of the content

        [Then (@ "Where" (. *) ' Display in ' (. *) ' ")]        public void Thenwheredisplayin (string p0, string p1)        {            webdriverwait wait = new Webdriverwait ( Webbrowser.current, Timespan.fromseconds (Ten));            Wait. Until<bool> ((d) = =            {                try                {                    assert.areequal (WebBrowser.Current.FindElement ( By.cssselector (p1)). Text, p0);                    return false;                }                catch (nosuchelementexception)                {                    return true;                }            });        

Webbrowser.current is a singleton example of Seleniumdriver.

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; Using techtalk.specflow;using openqa.selenium;using openqa.selenium.firefox;using openqa.selenium.chrome;using Openqa.selenium.support.ui;namespace seleniumtest{public    static class WebBrowser    {public        static Chromedriver current        {            get            {                if (! ScenarioContext.Current.ContainsKey ("browser"))                    scenariocontext.current["browser"] = new Chromedriver ();                return scenariocontext.current["Browser"] as Chromedriver;            }}}    

In this way, all validations can be reused by augmenting the scenery.

Iii. Summary

  NUnit: Unit test framework, which provides various assertions and test engines.

  Nsubstitute: A long time no, this is useless, used for virtual objects, unit testing is more common.

  Selenium: Implement Web Automation test, rely on him to open the test browser, automatic input and so on.

  Cucumber&specflow: Automated test framework, behavior-driven development, acceptance testing.

There are many other features that selenium and specflow have yet to dig.

Selenium+specflow Automated Test Day Practice (C #)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.