Tag Archives: Project

XAMVVM-01 A real walk-through of Xamarin.UITest with Xamarin.Forms!

Let’s take a chilled out walk through adding Xamarin.UITests to your Xamarin.Forms project! 😉

When I said chilled out, I meant literally a chill, no-fuss walk through adding UITests for your Xamarin.Forms project solution. There’s many articles and tutorials out there regarding this, but when I first started I couldn’t find a clear enough guide to begin with for myself, so I was stumbling around in confusion here and there until I self-learned a proper foundation. That’s why I thought of writing this post.

This is an attempt of sharing my experience and intuition of how to architect a better UITest structure for your Xamarin.Forms Solution helping you to get a clear and easy head start!

So I’m not gonna get into extreme baby steps, or details, but a clear fuss-free hands-on guide for starting off with your UITests, which I hope would give you a clear picture and understand of the whole shabang! After all I’m all about that solid project architecture!

Why UITests?

Hey, if you’re looking for a serious intro, please Google! I don’t like repetition of content lol.

Xamarin.UITests comes in handy when you want to have consistent assurance of the actual functionality of the app with the UI behaviour included. And between you and me, I actually love watching UITests being executed on Devices and Simulators, seeing you app actually being used like a human, giving you a whole feedback loop of the UI behaviour , is just an incredible experience! 😉

 

Let’s get started..

Just for the showcase of this awesomeness, I created a little App, which is called Textpad, where you simple take notes or texts of whatever you feel like. 😉 A very simple out of the box Xamarin.Forms app, and fully MVVM architectured code base with Prism. I named the solution as “XFWithUITest” just for this demo.

Whatever the default template of the Xamarin.UITest has provided, I have done several changes to it here and there for the clarity and of the code base as you will see in this article.

So I’m gonna walk you through a clean and well-structured manner of adding Xamarin.UITests to your project solution.

You can take a little sneak peak at it over here in my github repo:
XAMVVM-Playground/XFWithUITest

Structure is important!

There’s many ways to structure a UITest, but I like a clean separation of the elements in any solution architecture. Like here we’re going to separate our Tests from the actual Host projects.

So first, for the name of separation let’s add a Folder called “Tests” in your Xamarin.Forms solution. Yes, that’s the way to start!

Then let’s create our Xamarin.UITest project, right-click on the “Tests” folder in the VS Solution Explorer and go to Test tab and select Xamarin.UITest Cross-Platform Test Project!

Also pay extra attention to the Name and Location value for our UITest project. Append “.UITest” at the end of your project name. As of the location, make sure to add the path along with the “Tests” folder that we created above.

Next create a new Folder inside of that project called “Tests”, yes another one, which is where we’re actually placing our tests! Also create a new class called SetupHooks, which is where we’ll maintain all the hooks that are needed for our tests. (I’ll get into details for this in a later step)

Now it should look something like this!

Nothing more.

Delete anything else that’s unnecessary or not seen above! 😉

Off to next step!

Don’t forget the nugets!

Make sure all the necessary nuget packages are in place, which is just basically the following 3 nugets! yep that’s it!

Pay very careful attention here to the version of NUnit version 2.6.4, which is the minimum NUnit version supported by Xamarin.UITest as of today. (01/11/2018)

The deal with AppInitializer!

Now this right here is where your Tests will be firing up the app’s execution. There are many ways to structure this class and its functionality, but here’s my way…

This class comes pre-populated when you first create the UITest project, but I have made some changes of my own for the clarity of the code.

As you can see I’m passing in an extra boolean parameter “clearData”, which is to execute a clean instance of my App for testing.

I’m using the InstalledApp() call to load the Android and the iOS apps from the simulators, also I’m enabling the EnableLocalScreenshots() to get actual screenshots of my test instances as I wish. Yeah the fact that you can automatically capture screenshots during testing even when you run locally is really cool feature of Xamarin.UITests! 😉

Now instead of getting a hook on the InstalledApp(), you could use the path to the APK or IPA file using the ApkPath() or AppBundle() respective for Android and iOS, which is totally up to your choice.

Then I’m passing in the AppDataMode parameter according to my choosing of the “clearData” value.

SetupHooks holds the instances!

Remember earlier I created a class called SetupHooks? let’s set it up now!

public class SetupHooks
{
      public static IApp App { get; set; }

      public static Platform Platform { get; set; }
}

 

During UITests execution we’re holding a singular instance of the app in memory, which we’re calling through UITest’s functions to perform many operations, so to simplify that, here we’re holding a public static instance of the IApp and Platform object to be used in our Test cases.

Pretty neat eh! 😀

Let’s write the Tests!

Create a class called AppTests, which is where we’re going to place the Test fire up code and the rest of the tests for now!

namespace XFWithUITest.UITest.Tests
{
    [TestFixture(Platform.Android)]
    //[TestFixture(Platform.iOS)]
    public class AppTests
    { 
        public AppTests(Platform platform)
        {
            SetupHooks.Platform = platform;
        }

        [SetUp]
        public void BeforeEachTest()
        {
            SetupHooks.App =  
            AppInitializer.StartApp(SetupHooks.Platform, true);
        }

        [Test]
        ...
	// test cases begin here...
		
	}
}

 

There I have added the TestFixture attributes as required by NUnit to identify our tests, and notice how I have commented out the iOS platform, to show you that you could stick to one platform at a time for your ease of testing, instead of seeing failed tests in the Test Runner window! 😉

[SetUp] is where your Tests will initialize the actual App instance, thus retrieving a hook to the app’s instance for our Test cases to use.

You can see how I’m tying up the SetupHooks – Platform and App instances, through the initiation of the AppTests.

AppInitializer.StartApp(SetupHooks.Platform, true);

This gives a clean instance of the app for our tests cases to use, and up on your wish you could pass in “false” to the same method and get a data persisted instance of the app at anytime, anywhere in your tests! 😉

Now you’re all set to start writing your UITests, but before we begin I need you to check up on something else!

AutomationId for everything!

Whatever the UI element you need to get a hook on to or get a reference of, be it a Page, Button, Layout even a Label, you need to add a value to its AutomationId.

And make sure every AutomationId in a given Page context is unique for every element, otherwise the look up function will return all the elements that matches the given Id, which could lead to confusion in your tests 😉

IApp interface functions!

The Xamarin.UITest.IApp interface provides a whole bunch of functionalities for the app for us to play around with in order to execute our test scenarios.

Take a look here, Xamarin.UITest.IApp to see the list of powerful functions we can use. To name a few are Tap, Swipe, Scroll, WaitForElement and etc, to be performed on any given UI Element on the screen.

So now all you need to do is get a hook on any given element..

Getting a hook on an Element…

There’s several ways of doing this, most common is by the AutomationId of the Element

SetupHooks.App.Tap(c => c.Marked("Button1"))

Another is by the value of an Element’s property,

SetupHooks.App.Tap(c => c.Text("Click this Button!"))

Or you could do by even the Class name of the element. Choice is completely yours, pick the one best suited for your test case.

How to write a Test?

Now this is the coolest part, Xamarin.UITest allows us to get hooks on to UI Elements of the running App, then we perform actions on those elements and wait for the results and check if it resulted as expected through assertion using NUnit.

So its basically a little dance between Xamarin.UITest and NUnit Assertion! 😉

As a standard keep in mind to append “Test” at the end of each of your Test cases.

As you can see above I’m first waiting for the HomePage to appear, then I’m asserting it through NUnit. Then I look for the Label with “Hey there, Welcome!” text!

Action and Result, simple as that! 😀

Some advanced bits…

Here’s some advanced bits that could come in handy!

Getting the number of elements in a ListView
SetupHooks.App.Query(c => c.Marked("TextListView").Child()).Length
Getting an element in a ListView
Func<AppQuery, AppQuery> itemInListView = null;

if (SetupHooks.Platform == Platform.Android)
     itemInListView = 
     x => x.Class("ViewCellRenderer_ViewCellContainer").Index(0);
else if (SetupHooks.Platform == Platform.iOS)
     itemInListView = 
     x => x.Marked("<your listview automationId>").Index(0);

// change the index parameter to get the item you wish
Opening Context Menu in a ListView item
// pop up the Context menu in ListView item
if (SetupHooks.Platform == Platform.Android)
      SetupHooks.App.TouchAndHold(firstCellInListView);
else if (SetupHooks.Platform == Platform.iOS)
      SetupHooks.App.SwipeRightToLeft(firstCellInListView);
Enter Text into an Entry or Editor
SetupHooks.App.EnterText(
c => c.Marked("TextTitleEditor"), whateverYourText);
Wait for an element to disappear
SetupHooks.App.WaitForNoElement(c => c.Text("This label text"));

// either by Text or Marked as should work
Restarting the app anywhere…
// restarting app, persisting state

SetupHooks.App = AppInitializer.StartApp(SetupHooks.Platform, false);

Check out more here in this awesome git page: XamarinTestCloudReference

REPL is your tool!

Yes start using the REPL command line to see how your App’s UI is actually rendered by the native platform at any given execution time. Simply call this anywhere you wish in the UITests steps,

App.REPL();

And you’ll be presented with a CLI which will help you see the whole UI tree of the screen. Simply type “tree” in the CLI and you’re good!

Structuring the tests..

Now there’s many ways to structure all the test cases and scenarios, and there’s no strict standard way that should be followed, but whatever you’re comfortable or fits your project is totally fine and the choice is yours!

You could include all your Test cases in the AppTest class itself, or you can break them into separate classes regarding the Page, or the functionality type.

So for this demo I’m keeping all my UITest cases in the AppTest class itself.

Running the UITests locally!

Well now that we have structured the architecture, here’s the time for actual firing things up and you’ve got couple of things to remember!

You can run your Android Tests on Simulator and Device directly without any modification as long as you provide the right APK path or the App Id.

You can run your iOS Tests only on Visual Studio for Mac, and for the device you need to pass the provisioning details, and as of simulator, you need to pass the Simulator Id.

If you’re using InstalledApp() or ConnectToApp() in your AppInitializer, then make sure the app is already deployed or running in the devices or simulator.

Also make sure to keep your Devices or Simulators or Emulators screens switched on at all times, otherwise tests will break giving a waiting exception.

That’s it!

But I’m not completely satisfied with the architecture, so let’s kick it up a notch! 😀

Little cherry on top Architecture!

Like I said before there’s many ways to construct the architecture for your Test project, one of my favourite ways is by separating the test cases by Page Scenario, which I think is a much cleaner structure.

We’re going to create a base class, “TestBase” which has the constructor initiation and BeforeEachTest setup, then create a sub classes that inherits from it representing whatever the pages we have in the App.

It should look something like this!

And don’t forget you need to add TestFixture attribute for every single sub-class!

So what you’re gonna do is take apart all the Test cases you had in one class and move them into the related pages, simply cut and paste of the methods should do! Also on top of that you could abstract another layer of shared steps that we could reuse across these Page tests. 😀

Then it should give you a clean Test output as below.

There you go, all the Tests are now nicely aligned and structured under the given Page which it associates with!

Pretty neat eh!

So this above structure of mine is somewhat more of a simplification of the Page Object Architecture which is well explained here for Xamarin.UITests: https://www.codetraveler.io/

And even in this official github sample from Xamarin uses the same similar pattern: SmartHotel.Clients.UITests

Done!

As you can see its not that hard to set up your Xamarin.Forms project with UITest once you get the basic understanding of the moving parts and keep a clear structure in your head.

Now for some of you might be experiencing some issues with Xamarin.UITest, in which case I had too when I was first starting off. Therefore I ended up writing this post sharing my experience of solving them: Getting your Xamarin UITests to actually work! So if you’re having any issues getting your Xamarin.UITests to work in Visual Studio, that post might be able to help you. 🙂

Do check out my Github repo of this post:
XAMVVM-Playground/XFWithUITest

Thus concludes my real walk-through of Xamarin.UITests with Xamarin.Forms, in which I hope you got a clear understanding of how to properly structure your project and all the moving bits and pieces that gets the job done! 😀

Share the love! 😀

Cheers!

During The Final Year Project… The Reality from my Undergrad Eye…

The Final Year Project, for those who are undergraduates may know what am I talking about as for others, just wait till you get into a University, which is one of the most important pin points of an Undergrad Life. Some call it, “Thesis”, “Final Project”, “Final Research Project”, and so on, but nevertheless it is the Project that every single Undergrad is suppose to complete in order to graduate at their Final year of the Degree Program. I’m writing this based on my personal experience during I was an undergraduate at APIIT studying for my Software Engineering degree at Staffordshire University. Most of the people do not talk about publicly about this period of Life, moreover no one is bothered or everyone expects others to experience by themselves. But I thought of giving a little glimpse of it for all the curious young minds out there… 😉 I think it would be much better for a fresher to be aware of this huge storm they are gonna face someday ahead the years.

London-International-College-550x330[1]

The Heat…

It all begins at the beginning of the final semester of the final year, even though traditionally at APIIT, we have to start working on it according to a schedule from the first semester of the final year, well well  but everyone waits till the last moment to heat up themselves 😛 ! My fellow colleagues would definitely know about what am talking about 😉 lol Anyhow the heat increases, with the less time left, final assignment projects, final exams and so on, and added to that your supervisors and assessors of the project haunting you xD ! I still remember how we used to hide ourselves whenever we saw our supervisor or assessor.. Oh man, Good memories ! 😀 And also in the middle of all that, your parents and friends asking you about the project and and mentioning the fact that you are at the end of your degree you have to make them proud and all that talks ! -_-

The Stress…

The stress basically starts up with the heat which arises with the beginning of the final semester, which is caused by the facts, the biggest pin point of your degree life, the final project which everything depends on even your Honors class (1st Class, 2nd Class, so on) of the degree, speaking of which the FYP (Final Year Project) directly impacts on your final grade of the degree. Does not matter whether you have been a brilliant student through out your undergraduate life, if you screw this up even slightly, all that would be useless. This is the moment all your parents, cousins, friends, and neighbors are waiting to see the results of, which indeed is a killer stress having to imagine all those people around you staring at your final outcome. Specially the parents of yours who has spent a huge amount of money on your studies if you are an undergraduate of a private university.

The competition of course among the fellow batch mates, which is something always goes behind the back of everyone, in fact a known bitter truth no one likes to talk about. Among all that the fact that you have to deal with your final assignments, projects and exams, OMG talk about STRESS ! Imagine, having to study and work for your projects and exams while having to finish and entire research by your own and compile a full professional level undergraduate thesis by your own, YES ! that is what am talking about ! With in that very few months, you have to manage all that. This is a huge disadvantage for every single student, but which will eventually give a good experience for the student.
Even if you work hard, what if the final out come of the project does not suffice the objectives of your project ? Oh boy thinking that was one of the huge stresses I ever had personally. The stress is all those above added up together, like a frigging thunderstorm roaming around you, a huge rock on top of your head. Trust me this stress is the biggest an undergraduate would ever go through in his life.

Your Parents.. Responsibility.. Money…

The responsibility of the amount of money your parents have spent on you, whereas for us, having to be studying at private University where our parents had to pay from millions for our studies as payments. The funny thing is even though they have spent such a huge amount of money, we still can not guarantee proper grades, because does not matter how much you have paid it all depends on all your hard work as a student.
And the worst is that being in a private university which has a very strict line of academical rules and standards for course work for students, OMG, the pressure is even more higher. Knowing that even the slightest thing could screw up the whole degree which would waste all your parents money, would literally begin to give a heart attack every single time.

parentsweekend768x300[1]

Well that is of course if you care about the money your parents have spent on you and if you really wanna succeed in life with a good degree. This comes as a true motivation at times, well for me it was more of a motivation rather than a stress which is of course was a bit of a stress. Knowing that you somehow have to make your parents proud and prove them that they have not wasted their hard earned money on you, yes it comes from the bottom of the heart and when they see you working so hard to make them proud, nothing else would make them proud even if you loose. Some parents puts their whole life in jeopardy just to send you to a good university and lead you to a better life, specially in those cases the stress on the student is too damn high, and it is their responsibility no matter what…

Doing Something out of the Box ? Good Luck Son !

So I heard that you are hoping to do something out of the box yeah ? Oh well Boy, Good Luck ! I don’t about other Universities, but as in at where I studied doing something totally new and creative or totally out of the box for Your Final year Project, is like literally hanging your self. lol ! Its gonna be a huge risk that you would be taking, but it would all be totally worth it at the end IF you succeed ! but if you mess it up or if you are unable to fulfill the objectives you have defined at the beginning, oh well everything would go down the drain no matter how well you have done so far, what kind of a good research you have done. This would actually kill you when you are in the middle of all the stress, knowing that you are literally putting your neck out there for this new creative idea you wanna do for your project. And also when you tell people about it, (if you are an ordinary student) everyone would go like, Are you crazy ? You wouldn’t be able to finish it on time ? Is that even possible to do ? -_- and all that shit. Well if you are a well known talented student, they would go like, Oh WOW ! Thats awesome ! but isn’t that a lil risky ? 😛 lol either way all these outer environment would freak you out. And knowing the fact that You are on your own, oh boy, the pressure !

Sometimes this drives you crazy while you are going through all the final assignments and exams and crap -_- Yes I have been there. I still recall my Supervisor used to tell me, do you think you would have enough time to finish this up with the limited time and all these work you have got ? And every single time I heard that, it literally freaked me out, BUT I never gave up on my self, I knew my skill set and how i should achieve it using them and moreover I had a huge passion for the idea I had for my Project, which literally drew me to success. So hopefully I never had any doubts. This usually happens if your supervisor or assessor does not know you much as a student, even in my case he used to doubt me all the time, asking me whether I was able to do the work, asking me to show him the work I have done already every single time and so on. But do not get put down yourself, keep on working from your best and prove them wrong. 😉
Starting off is a huge problem whereas when you dont know where or how to start off prolly because no one has done that before, but do not worry, start somewhere and keep on researching. At the end of the tunnel you may find a light..

A Reason to be Proud..

If you think about it, in one way it is a reason to be proud of your self, when everyone else in your batch is doing some obvious random useless crap which has already been done before by the past seniors, YOU in the other hand is doing something EPIC ! something no one has ever done before. Trust me son, this factor will keep you on top of the world ! Even telling people that you are in to such a huge risk, such an innovative creation.. BOOM ! You would know the feeling..
Being different always feels good (well at least for my personally), but do not let it totally blind you with it. Keep an open mind, think of every single circumstances, always remind yourself of the risk that you are taking and be alerted.
If you are going through this, just know, You are taking a huge risk, but DO NOT GIVE UP and NEVER STOP BELIEVING ! NEVER LOSE YOUR PASSION ! no matter what they say or whatever happens. Just work hard ! work your *ss off ! 🙂 You will see a miracle at the end…

Your Friends and The Competition…

This is some kind of a dirty truth which no one would like to talk about. This is a moment where you get to choose between friendship and your personal success. But just because that you don’t have to be a total di**. Even though this is evaluated individually, there is still a competition going on between everyone in the batch, because at the end of the day everyone is trying to achieve the best GPA and get a good class from the degree, specially given the fact that 1st classes are given for only the best few.
Sometimes a good friend of yours would refuse to help you out with your project if they are jealous of you and they would probably ignore you. Be alerted, this happens with most of your so called friends 😉 or else they would lead you to a wrong path just to mess you up.. So be careful son !

Along with this some people decide to completely put down their friends in every single way possible, out of jealousy and out of being scared of other’s success. Which is really pathetic but some losers can not help themselves. lol 😛 Most of the time they would condemn your Project Idea, make fun of it in front of everyone else, discourage you saying that you can not do it, you wouldn’t finish it and so on such lame drama.. lol
Therefore make sure to stay away from such losers specially during your final year project and always surround your self with a supportive crowd of true friends.

You honestly don’t want to.. but you have no Choice…

During your Project days, with all the given stress and workload, you get extremely busy and sometimes unfortunately your friend comes up to you and ask for help with their project when they know you are good at it. But so sadly you are also extremely stuck and messed up with your own project in a totally different way which you can’t even figure out, at times like these you have to make a choice and like it or not you prolly would have to give priority for your own project having to turn down your friend who is in need… This is totally fair unless you are doing it out of your selfishness and competition.
I have personally faced so many situations like these during my project days. So what I did was trying to explain how I’m stuck with my one and how much more I have to finish in my, being politely said that its their responsibility be fair and understand the situation and approach someone else for help.
I had this one friend who was a girl, she asked me for some help with her project, and I said alright fine, I ll try my best but I’m also honestly messed up with mine. But later I forgot to get back to her with the help because I was really stressed and stuck with mine. Because of it until this day she does not speak with me. Funny enough she is the only one who acted like this when everyone else understood. So these kind of cases would be there once out of 10 times 😉
Well given the obvious reasons, its their responsibility to understand. It is a two way path actually you should be honest and give the fair reasons and they should understand the given circumstances. If they don’t cannot help it, this is about your future man !

No Sleep, No Appetite,  No Food,  No Mood !

This is some of the worst side effects you would face when you are going through your final year project, specially when there is only one or two weeks left for the submission. You literally do not feel like sleeping at all, you stay up all night long due to the stress, but for some people its the total opposite, they fell asleep even more often and sleep pretty well. lol 😛 Well after we humans are different from each other in nature. You get no appetite for food and you could stay without food even throughout a whole day.
Being moody is very common these days which comes obviously with the stress that you go through. This would be very annoying for your family members and specially your other friends, not to mention, obviously for your gf or bf. Well after all its their responsibility to understand the situation and deal with it.

I recall being up all night long coding on my project and coming to APIIT in the next day morning, being all moody and sleepy lol 😛 And I used to act very lazy and mean with everyone, looking all pale and sleepy.. oh oh and having my hair totally messed up, having a long beard looking like a cave man 😀 lol Everyone used to be like omg what has happened to you ? why are you acting like this and so on.. 😛 hikz xD Oh Yeah ! Good memories ! 😀
This actually drives you even more and sometimes it makes you even more harder knowing the fact that you should finish this off soon and get rid of this whole suffering.
So be prepared child !

being Extra Respectful and Scared for Lecturers and Admins.. lol

Being an undergrad for about 3 or 4 years you prolly have a clear idea whats the drill with interacting with Lecturers and the Academic Administration, knowing that they could screw you up from top to bottom if you mess with them. This is gets extremely cautions during the final year project time period. If you mess with a lecturer they could bring down your whole final year project results and like it or not, true or false, we all know this has already happened before for our seniors. Due to this reason you start paying extra respect for lecturers and being scared of them over the limit. 😛
And then the Admins, where when were at APIIT we had a very rude, unnecessary strict administration which we were really scared of thinking they would mess up our results or exams 😛 so we were acting like innocent mouses in front of them. lol 😀 Its actually an obvious reacting that comes from every single Final Year student knowing that you are going through the very final step and you have to be cool with everyone without making any issues which you know would bite you in the back 😛 !

The Insanity and Nonsense Blast !

So getting back to the stress, this one of the EPIC-EST outcomes of it in mostly every single student ! You may see some of your batch mates even your own self going completely insane due to the stress, where as start playing around nonsense even in the middle of all the hectic serious workload, randomly shouting out loud in the middle the class or the lab, running around, hurraaaying even for the tiniest thing, dancing in the middle of the lab and so on, oh yeah the list goes on… xD Specially I’m personally a lot experienced regarding this, where as I was one of those victims who had such side effects to the extreme level. Even today if you talk to any of my colleagues, they would tell you xD  😛
Oh yeah, so much of epic memories with that… 😉 and be warned child, your time is ahead of you ! 😛

So…

So this is some of the reality experience I had during my Final year Project when I was an undergraduate at University. Well of course this is totally based on my own personal experience at APIIT Sri Lanka, if you are a student from other University it would be different, but in common these facts are true for most of the undergrads. I’m just leaving these experiences in my blog for you guys out there, just to mark some of the unforgettable experience I had at my University days, hoping you would be able to gain something from them and add more of you own to it.
Well as now I am a graduate and working for some big a** corporate company I would never get the chance to go back to those amazing days, and someday you will also get to this point in your life, and make sure you wouldn’t regret the time you spent during the Final Year Project, the last few weeks at your University.
So get the maximum of it, help out your friends in possible ways without being selfish all the time, do not mess with the lecturers 😛 , take some risk, do something different for your final thesis, work yours a**es off, and play some random nonsense just to have fun and get rid of stress 😉 making some good memories ! 😀
Behold the Secret Recipe ! 😉

Good Luck for all you folks out there ! 😀 Have an EPIC time !

(Image Sources – Google, 2014)