Selenium RC In C# as a Console App: Another End-To-End Example

Posted on February 2, 2010. Filed under: open source, test automation, Tools |

The purpose of this post is to show people how to wrap a Selenium RC test up into a console app (*.exe) so can been executed from the command line.  This is a solution makes it where you don’t have to have NUnit involved.

Déjà vu all over again! Another basic Selenium example. What the heck!? Can’t this guy do anything else?

Well, I agree this is somewhat repetitive, but I hope that this sequel will be in the league of Empire Strikes Back or Star Trek: The Wrath of Khan. Both movies, though they were sequels, were arguably greater than the originals. These sequels introduce us to the likes of Ricardo Montalban playing “Khan” and Billy Dee Williams playing “Lando Calrissian”.  And of course,  a muppet playing “Yoda”.

Of course, many sequels start off with the desire to be Empire, and instead they end up being:

  • Caddyshack II
  • Beastmaster 2: Through the Portal of Time
  • Speed 2: Cruise Control
  • Batman and Robin (No, we don’t need nipples on the Batman suit, Joel Schumacher.  But thanks for asking.)
  • Mannequin: On the Move.
  • Or the biggest sacrileges of all time Godfather III
  • And Episode I (Empire, it is not!).

My hope is that this post doesn’t suck like those movies.  At the very least it’s nipple and Clooney free.


First off, you need to get all these things (if you don’t have them):


Install instructions for the downloads:

Selenium RC
-No installation necessary. Just find a permanent location and unzip it there. I unzipped mine at C:\ just to make things simple

Firefox, Visual Studio Express, and Java
-Just run the respective installs with all defaults selected.

Selenium IDE
-To install, right click on the file and select “Open With…”
-Select Firefox in the programs list. If it’s not in the immediate menu, browse to it. (default location should be “C:\Program Files\Mozilla Firefox\firefox.exe
-When Firefox launches, click button in the dialog box that says “Install Now”.
-After the install of the plug-in, hit the “Restart Firefox” button when you see it.


Phase One: Record a Test using Selenium IDE

Okay, so, now that you have the tools, we’re going to record a simple test in Selenium IDE. Even though we want to eventually run the test in Selenium RC, Selenium IDE is a great tool for getting the basic test recorded since it’s all UI point and click.

  • Start up Firefox.
  • Click on the “Tools” menu and click on “Selenium IDE”
  • (Take your time to explore the Selenium IDE form)
  • Notice that it’s already recording.  The red circle button on the right side is pressed in:
  • Type “www.google.com” the main Firefox browser address bar and navigate to it.
  • In the search box, type in “thetestingblog.com” and hit the “I’m Feeling Lucky” button.
  • Notice in your Selenium IDE window that steps are being recorded.
  • With any luck, you hopefully landed on this blog’s home page.
  • Highlight the text “Daniel Brown” on the page, right click.  You should select the option that says “VerifyTextPresent Daniel Brown”.  See below:

Screenshot_VerifyTextPresent

  • Okay, we got our test recorded.  Now let’s run it to make sure it passes.
  • Unclick the red circle button to turn off recording.
  • Click on the green play triangle with the single bar to run the test

Screenshot_PassedIDETest

  • All green, it passed.  Good.
  • Now we want to convert this test to C#.
  • Select “Options ->Format -> C# – Selenium RC” from the Selenium IDE window.

Screenshot_ConvertToCSharp

  • Next select all the C# code and copy it.

Phase Two: Setup the C# Console App

  • Open up Visual Studio
  • Select “File ->New ->Project”
  • In the New Project window under project types, select “Visual C# ->Windows”
  • Select the “Console Application” Template and name it something like “TestingBlogSeleniumTest” and click “Ok”.
  • It will create the project along with a file called “Program.cs”. Paste your SeleniumIDE test into Notepad. You’re going to take pieces out of the test and put it in “Program.cs”.

  1. Add the using references from the SeleniumIDE test.  Replace any that are there.
  2. Add the “ISelenium” and “StringBuilder” object references inside the Main() method.  As you see, I removed the “private” access control prefixes.  We don’t need them.
  3. Add the body of the SetupTest() method after the object references.  (I put a comment to designate that it was part of the setup.)
  4. Change “*chrome” to “*iexplore” for Internet Explorer.  Use “*firefox” for Firefox.  (There are other browser options, but those work best.)
  5. Change the URL to the site you start your test on.  In this case, change that URL to “http://www.google.com/” since we’re starting from Google.

6. Paste body of the TheUntitledTest() method into the Main() method.

7. Paste body of the TeardownTest() method into the Main() method.

8.  Get rid of the Try/Catch blocks on Teardown.

9. Get rid of the StringBuilder references.

10.  Get rid of the Try/Catch block in the test body, replacing it with an if statement that writes to the console window if true (See my code below).  Notice that I have to cast the Selenium.IsTextPresent statement as a boolean.  I don’t understand why it doesn’t work without it because the return type for that method should be boolean.  But whatever.  I’m just dummy tester; what do I know?

  • Next we need to add all the references so this thing will run.
  • Go to the solution explorer, and right click on the “References” and select “Add Reference…”
  • Hit the “Browse” tab and navigate to where you unzipped your SeleniumRC files.  Look in the dotnet client driver folder.  Here’s the path to mine:

C:\selenium-remote-control-1.0.1\selenium-dotnet-client-driver-1.0.1\

  • Once you navigate to where the proper *.dlls are, select all of them and click “OK” to add them to the project.  (I know you can probably get away with adding less, but let’s keep it simple.)

Add References

  • Build the project to see if it works.  (Mine worked.  Hopefully yours did too.)

Phase Three: Running the Selenium RC test Console App

  • In order to run the Selenium RC test, you first have to have the Selenium RC server running.  The Selenium RC server folder should be in the files you unzipped.  Normally, I have a batch file on my desktop created to run the Selenium Server, but for our purposes, we’ll just run this from the “Start -> Run” commandline, using this command:

java -jar C:\selenium-remote-control-1.0.1\selenium-server-1.0.1\selenium-server.jar

  • You should see some a dos window popup, and you will see something like the screenshot below.  DON’T CLOSE IT WHILE TESTING; IT NEEDS TO STAY RUNNING.  If you don’t have Java installed, this won’t work.  But most people should already have Java.

SeleniumServer

Next you need to select Debug from your Visual Studio menu and select “Start Without Debugging”. (I’m choosing this option because it doesn’t close the console window after the end of execution.  The debug option does.)

You should see the Selenium window(s) pop-up.  And it should do it’s thing.  When it’s finished, you should see something like this:

So, where is my test executable?  Well, it’s in the bin\debug folder of the project.  For me, the path to it looks like this:

C:\Documents and Settings\dbrown\My Documents\Visual Studio 2008\Projects\TestingBlogSeleniumTest\TestingBlogSeleniumTest\bin\Debug\

So, what do I need to run the program?  Just take the executable file and the dll’s.  Make sure the dll’s are in the same folder as the test when you execute it, otherwise you will get a big fat error.  If you send the executable to someone, make sure you send the dll’s too.

Remember if you port that executable to another computer, it needs to be a Windows box with the .NET framework installed and Selenium server needs to be running.  I hope this actually helps someone.  I’m going to post some tricks to “sex up” your console app.  Be looking for them shortly. ;)

Sorry, I still haven’t figured out Selenium GRID good enough to post on it.  Maybe Marisa could post on it?  She’s awesome like that.

Advertisement

Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

32 Responses to “Selenium RC In C# as a Console App: Another End-To-End Example”

RSS Feed for The Testing Blog Comments RSS Feed

your explanation is so good.i did it’s worked.

Excellent, thanks for sharing the info.

It would be nice for part 2 of this example to show the Selenium grid implementation? This is a great starter example. Thanks for the info.

Keith

[...] RC, преобразованный в консольное приложение: краткое руководство к [...]

Hi,
This was very useful but I’ve only got as far as step 10 and I keep getting 3 errors and 3 warnings! The warnings i’m not sure are pertinent to this issue but maybe you can make sense of it. Thanks!

Errors:
- The type or namespace name ‘Selenium’ could not be found (are you missing a using directive or an assembly reference?) – Line 6
- The type or namespace name ‘ISelenium’ could not be found (are you missing a using directive or an assembly reference?)-Line 14
- The type or namespace name ‘DefaultSelenium’ could not be found (are you missing a using directive or an assembly reference?) – line 18

if you need to have a look at my code let me know and i’ll send it to you.

Cheers!

TJ,
Don’t forget to add the references as specified in the tutorial, step 10 (4th point as of today). The Selenium namespace comes from the ThoughtWorks.* DLLs ;)

Nice tutorial!
You can still run NUnit from the command line: “nunit-console something.dll”, though, if that’s the main purpose!
Hum, and it seems a bit pointless to me to convert all NUnit assertions mechanism into an if-else block. Oh, and I did not need to cast the selenium.IsTextPresent(“..”) for myself!
Thanks for sharing, anyway! I’ll be sure to follow this interesting blog!

That’s why code is great. So many ways to solve problems. Thanks for your insights. And thanks for reading the post. :)

I get the same error:
- The type or namespace name ‘Selenium’ could not be found (are you missing a using directive or an assembly reference?) – Line 6

I’m using VS 2010 on W2K8 R2. I have the RC version from February although I only have .Net 4.0 on the machine. Is this a .Net incompatability because its reliant on something from 3.5?

Hi,

When I run the script using IDE it works fine. But when I run using RC with .NET driver in C# it opens up browser and fail to identify the controls ( simple buttons ) its an https page.
Are there any tricks to get this working in Se RC with C# ?

Ok, found my own issue earlier, in Visual Studio I needed to change the .Net type from 4.0 client to plain 4.0. After that things worked fine.

Wow, thanks for sharing that Michael. I know for a fact that you’re not the only one having a problem like that. I wasn’t sure if anyone running VS2010 was able to get Selenium working. Again, thanks for sharing.

My script works fine in IDE and for *iexplore but they fail in *firefox.
Is there any workaroud to as why do we get element not found in firefox but works fine in *iexplore and IDE ?

Here is the server log snippet
08:09:14.614 INFO – Got result: OK on session 165c0d3ec2034e0cbb0335a2a49088dd
08:09:14.614 INFO – Command request: waitForPageToLoad[120000, ] on session 165c0d3ec2034e0cbb0335a2a49088dd
08:09:14.630 INFO – Got result: OK on session 165c0d3ec2034e0cbb0335a2a49088dd
08:09:14.630 INFO – Command request: type[f1, userlogin] on session 165c0d3ec2034e0cbb0335a2a49088dd
08:09:14.645 INFO – Got result: ERROR: Element f1 not found on session 165c0d3ec2034e0cbb0335a2a49088dd

Thanks a ton.

very very nice tutorial!!!

Hi daniel ,
Can any you please post a topic on handling pop up and alert messages(javascript)using selenium RC .It ll be really great .None of the commands like getalert , ChooseOkOnNextConfirmation is detecting the popups in my application !!

Madhu, I don’t have a good answer for you right now. This is definitely a struggle in Selenium. I think the guys writing Selenium need to come up with a clean solution for handling these cases. You’re right the commands to help don’t always get it down.

If I find some effective tricks to handling Popups, I will post a blog entry on it. Thanks for the idea! Now to really research it… :(

hii daniel
Thanks for the tutorial its really helped me a lot

Can any1 knw how to use selenium for windows application

thattil,

Selenium can’t really be used outside the web browser context (it uses XPath, Javascript, etc to tell what’s what and “do stuff”.). Windows apps don’t really run the same as web apps. SHORT ANSWER: I don’t know of a way to make it work with a Windows App. But if you do figure it out, that’s a blog entry. :)

hi
i am using C# it works well when i use one link for testing…….
but when it comes to use two links one after the other it dose not works
Solution :- i have to separate the two link in two different classes

Can any 1 tell y its happening

Well I do something like this (my Root URL is opened with the selenium = new DefaultSelenium() command early on):

selenium.Open(“/”);
selenium.WaitForPageToLoad(GlobalSettings.TimeoutVar);
selenium.Open(“/registration”);
selenium.Open(myUrl);
selenium.WaitForPageToLoad(GlobalSettings.TimeoutVar);
selenium.Click(“dashboard_ContinueButton”);
selenium.WaitForPageToLoad(GlobalSettings.TimeoutVar);
selenium.Click(“dashboard_ContinueButton”);
selenium.WaitForPageToLoad(GlobalSettings.TimeoutVar);

Is that close to what you do, or do you have a different kind of setup? Basically this script does a simple registration, opening the default site, then a sub-site with a page that only needs some click-throughs. I kept out the data entry since that wasn’t part of your question.

hi
thanks for replying i ill try!!!!!!!!!!
Can any1 tell how to read data from the text box as it ill b helpful for validation
in selenium….
please do reply

Try this good tutorial from Matt Heusser it should get you going: http://searchsoftwarequality.techtarget.com/tip/0,289483,sid92_gci1516589,00.html

This article is awesome. Good job.

I need to validate the fileds with number of values. until that page should not go further. any thought on it?

hey its really help me ….thanks…m done with console application but still not with nunit…it give me some error regarding assembly…..

[...] Selenium RC In C# as a Console App: Another End-To-End Example [...]

I was able to run this in VS2010, except in a coded UI Test instead of console app!

I have another query here, I am trying to develop tests as Windows Application and have modularised my approach. I have Main.CS, CommonFunction.CS, Feature.CS. I am trying to execute from Main.CS, control goes to Feature.CS and then CommonFunctions.CS to invoke browser. But when the control comes back to Feature.CS, I am getting Object Reference not Set exception.
Upon debugging I have found out that SetUp section must be present in all the class files, but the drawback is that having Setup section in each Class file, invokes new browser every time. Is there a way to over ride this and continue with only 1 browser being invoked.
Hope my explaination makes any sense.
Note: I am not using NUnit to execute my scripts, but using the C# Express Edition to execute.
Thank you in advance for your help.

Hi Yeshwant – I’m so sorry I just now saw your comment. Regarding SetUp instantiating a new Selenium driver/browser window – what I do is call Selenium’s stop() method in TearDown. I write my Selenium tests in fitnesse, but I’m sure nunit has got to have a notion of TearDown. I hope that helps.

Hi Marisa,
Sorry for replying in so late. I figured out a way to achieve what I was trying to get. I wrote [TestFixtureSetup] in Initialise.cs class and instantiated it in other classes and this solved my problem. I have a decent framework in place now.
Thank you,Yeshwant

Thank you that was sooo helpful.


Where's The Comment Form?

Liked it here?
Why not try sites on the blogroll...

Follow

Get every new post delivered to your Inbox.