Unit Testing and other UWP interesting stuff

Hello my dear developers!

How do you feel today?

These days I had to get started with UWP (which I’ve never used in my life).

No panic, it’s the old xaml c# way, bindings work, IOC works, etc.

Just for the sake of testing it I assembled a little project with Unit Test and MVVMLight library and Unity (IOC Container), but first of all it took a little bit of time to assemble it all (6 hours, searching for a web service, searching how everything was done on uwp, bootstraping, trying template stuff that I didn’t get to work, etc). I’m not saying it’s a lot of time for a test from 0 to having a decent data consuming application, but there was room for improvement.

The real tricky part came when I tried to unit test a UWP library, I just assumed everything would work as always, you know… Adding a test project and so one, but my surprise was that I wasn’t able to get a reference for my UWP library or UWP Application project, so I searched online and found this article Unit Test on UWP from Not only .net and was quiet help full.

So just for the clearness I would start the following way:

  1. Create an app project
  2. Create a UWP library project
  3. Create a Unit Test App

Since the Unit Test app is the trickier because and is not on test projects templates, here is an image of how its done

00unitetsapp

So the project structure is something like this

01-unittestprojectstructure

I’d run my first test just for the fun of it

02-passing-test

Now comes the XUnit part (RMB on the unit test project an Manage Nuget Packages)

03xunit

Now delete the test reference

04-delete-testreference

and let’s tweak the project.json to update our refernces to uwp and xunit

Original after nuget

05-original-project-json

Final one06-tweaked-project-json

Now let’s run our first XUnit test

07-xunit-passing-test

There you go if you want more info on XUnit go to the documentation on github

 

I hope this is as useful for you as it was for me an from now on I’ll try to improve my MVVM IOC project assembling time starting for this incredible template called t10, It’s great and even has its on MVA Course, take a look here it’s a dream come true.

Happy coding and remember…there is life beyond coding🙂

Advertisements

101 Jasmine js unit testing

Hello my dear developers!

How do you feel today?

For some time now I’ve been very fond of unit testing and more importantly TDD (Tests driven developement) since it changed my mind and lowered the stress impact on my work.

So when I found that it was possible to unit test your front-end’s javascrtipt I really wanted to learn Jasmin.

Jasmine sort of couples both of my passions ALM (Application Lifecycle Management) and Unit testing, since BDD (Behaviour Driven Development) starts at defining your tests like user stories for startes and then allows you to continue refining your tests to the very final result.

I’ll cut the chitchat and get to it!

To get started with Jasmine js you have to go at  Jasmine’s docs page go for the latest version (at this time 2.5.2). Once you are at the page scroll down to the download section and get the stand alone release, download it to your desktop and you are good to go.

01downloadjasminestandalone
Standalone release at Jasmin’s website

Now open Visual Studio:

  1.  Go to the File menu and open Website (File/Open/Website (Shift+Alt+O)) and select your Jasmine’s stand alone release folder.
  2. Run it and Visual Studio will ask you to create a web.config file and you simply click OK and go to  “yourproject”/specrunner.html .
  3. You see some sample tests about a song player.

 

02-vs-open-website
Open Website at Visual Studio

Now let’s create our first spec. Erase everything on spec folder and on the src too. On the spec folder create your first spec (something like “myFirstUnitTestSpect.js”) and write something along these lines:

describe("MyFirstUnitTest",function(){
    it("should be a unit test", function(){
        //TODO add functionality
    });
});

    Describe is a Jasmine’s function, that gives name to the unit test and it describes what happens on the unit test; something like given MyFirstsUnitTest and it should be a unit test.

Now go to your specrunner.html and modify the js section to leave it like this:

<!-- include source files here... -->

  <!-- include spec files here... -->
  http://spec/myFirstUnitTestSpect.js

If you run your website again and launch the spec runner you’ll get your first passing unit test.

03first-nunning-test
First Passing Unit Test

Happy coding and remember…there is life beyond codding🙂

When working with files

Hello my dear developers!

How do you feel today?

These days I’ve been reviewing some code involving JSON and file managing, as always you are supposed to know the 101 on how to work with files, storing, opening, editing, etc.

But the tricky thing always comes when you want to make sure that a file exists and you get false positives and everything starts throwing weird exceptions that you didn’t expect. You at that point start spending your precious time chasing ghost’s through a hundred break points, stepping in to execution and such.

“Good if I could remember… I’ve had this one before”, I thought. There’s some option called open create or something (FileMode.OpenOrCreate) but now I’m using static methods from File Class such as WriteAllText() or ReadAllText() and those don’t take this options. Da@# it!

So after some thinking and a lot of rush I went in to “I don’t give a crap about technical debt, I just wanna finish mode” and started writing the following code every time I wanted to get a file from storage either to read o write on it.

 

var fs = File.Open(path, FileMode.OpenOrCreate);
fs.Close();

 

“God this is crappy code I can’t believe I did it again, now if this doesn’t work I’ll have to go fixing it all over the project”, I felt.

Thereafter my guilt grew unbearable so I started developing a much neater code that centralizes everything on a method called GetPath, that has a bool createIfNotExists that when set to true it executes the code shown before and else you can do things however you like regarding how to ensure file existence.

public string GetPath(string fileName, string fileExtension, bool createIfNotExists = false, string folderPath = "")
{
    if(string.IsNullOrWhiteSpace(_basePath))
    {
        throw new IOException("File Manager needs a basePath to work with");
    }
    string path = null;
    if (!string.IsNullOrWhiteSpace(fileName) && !string.IsNullOrWhiteSpace(fileExtension))
    {
        if (fileExtension.Contains("."))
        {
            fileExtension = fileExtension.Replace(".", "");
        }
        if (string.IsNullOrWhiteSpace(folderPath))
        {
            folderPath = "";
        }
        else if (!folderPath.EndsWith(@"\"))
        {
            folderPath += @"\";
        }
        //this ensures directory creation
        if (!string.IsNullOrWhiteSpace(folderPath) && !Directory.Exists(folderPath))
        {
            Directory.CreateDirectory(folderPath);
        }
                
        var baseAndFolder = string.Format(@"{0}\{1}", _basePath, folderPath);
        if(!baseAndFolder.EndsWith(@"\"))
        {
             baseAndFolder += @"\";
        }
        baseAndFolder= baseAndFolder.Replace(@"\\", @"\");
        path = string.Format(@"{0}{1}.{2}", baseAndFolder, fileName, fileExtension);
        path = path.Replace(@"\\", @"\");
        if (createIfNotExists)
        {
             //this ensures file creation
             var fs = File.Open(path, FileMode.OpenOrCreate);
             fs.Close();
        }
    }
    return path;
}

 

If you’d like to have a pick at the complete project you have it here it’s the Things that I forget when I sneeze project evolved.

I know that this is not the most optimal solution so I encourage everybody that comes with a better one to leave a comment on how to improve it in any way.

Happy coding and remember…there is life beyond coding🙂

Angular: 101 no code how to get started

Hello my dear developers!

How do you feel today?

These days I’ve been focusing on Angular.js 1.x.

The thing is that there are many tutorials out there but I found one that didn’t work on youtube and had to rewrite it.

The aim of the tutorial was to write an Angular.js application with no code, today this isn’t possible but it is close, so let see… you just have to register your app name on a js file, reference it in your index.html an you are good to go

index.js

 


(function () {
    'use strict';
    angular.module('yourAppNameGoesHere', [
    ]);
})();

index.html

<body ng-app="yourAppNameGoesHere">
<!--...-->
< div class="row" >
<input type="text" placeholder="Enter your name" />
<h1 ng-bind="goodPracticeBindedName"></h1>
</div>
<!--...-->
<scrip src='../Scripts/angular.min.js'></script>
<scrip src='app/index.js'></script>
</body>

If you want you can have a look at the code

I hope it works for you.

Happy coding and remember…there is life beyond coding🙂

Unit testing sharning json file as app config

Hello my dear developers!

How do you feel today?

In many projects, I’ve been told to change the model of app . used for some other, for instance in a cross-platform mobil app I had to read the configuration from a config.json file that could be changed every week being sent by e-mail to the device. Obviously the file had to be overridden.

So,that, presented a challenge for unit testing my classes.

This might be conflicting since I now that ConfigurationManager is so good at it’s job and so on, but my concert was to test he exact same setting from my front end in my unit tests, so I found this nice article that explains how to share items as a link

Using this I could write one file in my “main” application and consuming it from the unit test project as a link thus not having to maintain two different sets of configurations.

As I said this is for a very specific scenario and I know that common sence dictates using app.config and web.config having two scenarios for preproduction and production, but I thought that if some one was interested I’d just post it.

Just for the sake of having it written somewhere, always remember to set your Copy to Output Directory option to Copy always for your json files, since the default is Do not copy.

config-json-copy-always

I hope this helps

Happy coding and remember…there is life beyond coding🙂

JSON: Dictionary with case insensitive keys

Hello my dear developers!

How do you feel today?

After some time working with Json I’ve realized that properties on .net use Pascal casing and nodes of json use camel casing. So to prevent problems with case sensitive keys I found this neat trick to avoid having to mess around with casing.

 

var dic= JsonConvert.DeserializeObject<Dictionary<string, object>>(_jsonSample);
_responseObj = new Dictionary<string, object>(dic, StringComparer.InvariantCultureIgnoreCase);

so you could do this

 

List result = new List();
//string resultsJson= _responseObj["responseData"].ToString();
string resultsJson = _responseObj["responsedata"].ToString();
var res = JsonConvert.DeserializeObject(resultsJson);

 

If you want to see it in action you can find it at JsonManager.cs of my code

Happy coding and remember…there is life beyond coding🙂

Inline if

Just for the sake of NullPointerException handling I like to use Inline ifs.

The inline if is a wonderful way to avoid having to write 3 lines of code for a very simple if block.

I tend to forget it all the time.

The syntax goes like this

<condition>?<true>:<false>
string sValue = v.Value != null ? v.Value.ToString() : "\"null\"";

if you want to see an example of this you could find it at the Program.cs of my code

Happy coding and remember…there is life beyond coding🙂