Introduction

In this article you will have basic introduction of Unit Test and will learn how to write Unit Test in C#. Writing test case is an inevitable part of software testing. Testing software is a real challenge, because there are so many types of test cases that come in so many different shapes and sizes. In order to learn how to write good Unit Test, we must first understand as to what is Unit Test and why do we need it. So lets learn that first

What do you mean by a Unit Test ?

Unit Tests simply verifies that individual units of code (mostly functions) work as expected. Usually you write the test cases yourself, but some can be automatically generated. Performing unit tests is designed to be simple, generally the tests are written in the form of functions that will determine whether a returned value equals the value you were expecting when you wrote the function. The objective in unit testing is to isolate a unit and validate its correctness. A manual approach to unit testing may employ a step-by-step instructional document.

Why do we need Unit Test ?

One of the most valuable benefits of Unit Tests is that they give you confidence that your code works as you expect it to work. Unit Tests give you the confidence to do long-term development because with unit tests in place, you know that your foundation code is dependable. Unit Tests give you the confidence to refactor your code to make it cleaner and more efficient.

There are few reasons that make you understand why a developer need to design and write out test cases to make sure major requirements of a module being validated during testing:

Unit testing increases confidence in changing/ maintaining code. If good unit tests are written and if they are run every time any code is changed, we will be able to promptly catch any defects introduced due to the change.

Unit testing finds problems early in the development cycle. This includes both bugs in the programmer’s implementation and flaws or missing parts of the specification for the unit.

Codes are more reusable. In order to make unit testing possible, codes need to be modular. This means that codes are easier to reuse.

Unit testing may reduce uncertainty in the units themselves and can be used in a bottom-up testing style approach.

Development is faster.

Codes are more reliable.

Easy to automate.

Lets start the show – Create your First Unit Test(Step by Step)

In this article, I would like to show that unit tests are quite easy. Unit testing is a way for the programmer to make sure that the code that is written is fully functional and works the way it is supposed to work. Unlike the standard testing method, when a piece of code is ran an the developer or tester manually feeds the values, unit tests can test specific methods/functions (or any other code elements) by providing the test data in code.

One of the fundamental principles of unit testing is to follow TDD(Test Driven Development) where we have to write tests first, and then write the simplest code that will make the test pass. Here I am going to follow just opposite approach to make you learn how to write and Test code first. Later we will discuss TDD concept. In this article we are going to follow different approach where we will write simple code first, and then create the Unit Tests based on the possible situations. As discussed earlier, we can also write Tests first, and then write the code that will make the test pass. It depends upon individuals which one of the way to follow to test code.

Here I’ve written a basic program which can be easily understandable by any novice who’ve just started to learn C# and want to learn how to write unit test.

It will open a ‘Add New Project‘ window. Follow the given steps to create and add Unit Test Project.

Click on Test

Select Unit Test Project from list of available templates.

Write name of project. Here we are using BasicMathTest and then Click on Ok button.

It created BasicMathTest project along with BasicMath Project whose functions need to be tested. To access all four method of BasicMath in test project we need to add it reference in test project. Take a look in below image to know how to add.

Right click on Reference of MS Unit Test Project

Click on Add Reference

It will open a Reference Manager window. To add reference, click on Projects – Solutions – BasicMaths and click on Ok button.

You can see in below image that the reference has been added .

BasicMath – Having all functions which need to be tested

Microsoft.VisualStudio.QualityTools.UnitTestFramework – It contains all classes and methods that provide unit testing support.

We can see that in every test function We use the Microsoft unit test framework for managed code Assert.AreEqual method to verify that the ending balance is what we expect.

Build and run the test

To build and run the test.

Either go to Solution Explorer (Ctrl +Alt+L) and right click on Solution ‘BasicMath’ and Click on Build Solution or go to Build Menu (Alt + B) and Click on Build Solution.

Choose Test Menu -> Run -> All Test. Or instead of this step you can follow given step also

Go to Test Explorer and Click on Run All to run tests for all test methods .

As the test is running the status bar at the top of the window is animated. At the end of the test run, the bar turns green if all the test methods pass, or red if any of the tests fail.
You should now see something like this :

In this case, If the test does fail. The test method is moved to the Failed Tests. group. Select the method in Test Explorer to view the details at the bottom of the window.

Analyze the test results – The test result contains a message that describes the failure. For the AreEquals method, message displays you what was expected (the (Expected<XXX>parameter) and what was actually received (the Actual<YYY> parameter). In this case, Message was Assert.AreEqual failed. Expected:,Actual

Rerun the Test – In Test Explorer, choose Run All to rerun the test. The red/green bar turns green, and the test is moved to the Passed Tests group.

Cheers! We learned how to write Unit Test.

TDD(Test Driven Development) Implementation using Unit Testing in C#

As we discussed earlier in this article that most of the developer follow write Test first then Code Later approach, we are going to learn TDD approach and how to use it.

Test-driven development (TDD) is primarily a specification technique with a side effect of ensuring that your source code is thoroughly tested at a confirmatory level. TDD is a software development process that relies on the repetition of a very short development cycle: first the developer writes an (initially failing) automated test case that defines a desired improvement or new function, then produces the minimum amount of code to pass that test, and finally refactors the new code to acceptable standards.

A significant advantage of Test-driven development (TDD) is that it enables you to take small steps when writing software. As for example, Let us assume you add some new functional code, compile, and test it. Chances are pretty good that your tests will be broken by defects that exist in the new code. It is much easier to find, and then fix, those defects if you’ve written two new lines of code than two thousand. The implication is that the faster your compiler and regression test suite, the more attractive it is to proceed in smaller and smaller steps. It is generally prefer to add a few new lines of functional code before recompile and rerun tests.

The motto of test-driven development is “Red, Green, Refactor.”

Red: Create a test and make it fail.

Green: Make the test pass by any means necessary.

Refactor: Change the code to remove duplication in your project and to improve the design while ensuring that all tests still pass.

The Red/Green/Refactor cycle is repeated very quickly for each new unit of code.

Let’s Implement TDD using MS Unit Testing

Let’s take exact same sample of code which we’ve used earlier in this article. We will create four basic function like Add, Substract, Multiply and Divide which will need to be tested. In earlier example we’ve written code first then Unit Test later but as this is TDD implementation we will write Unit Test first then will write code later.

To Write Unit Test. Follow the steps given in below image.

Create new project. Click on Test.

Click on Unit Test Project

Write Project name. Eg – BasicMathTDDTest and then Click on Ok button

you will get default code template as given below to write your test code.

As you can see that there are two test method Test_AddMethod and Test_MultiplyMethod and both method is using BasicMaths class, Add and Multiply method which is not yet defined. When we run this application you will get error as given below :

To make MS Unit Test run, we need to create BasicMaths class and add reference to Unit Test project. Follow given steps to know how to create BasicMaths class and adding reference to MS Unit Test Project.

Right click on Solution ‘BasicMathTDDTest’

Click on ADD

Click on New Project

It will open a Add New Project window where you have to follow given steps

Click on Visual C# ( If you are writing code in C# language )

Click on Console Application

Write Name of Project, Here Project Name is BasicMath and click on OK button

Now write Add and Multiply Method under BasicMaths class for which we have already written MS Unit Test. Code will look like as given below

After writing code you can see that there is 0 references of BasicMaths class as well as Add method function but these function is already being used in MS Unit Test project. To make it accessible we need to add this project to MS Unit Test Project reference.

Once you add reference, Its time to run Test. To run Test you can either go to Test -> Run -> All Test or move to Test Explorer and click on Run All. After running Tests you will see output as given below

Both Test Method Test_AddMethod and Test_MultiplyMethod is failed. To Know why These method failed while Testing click on each Method and read the reason.

In Test_AddMethod Assert.AreEqual is supposed to give 41 as actual value but we are expecting 21. It must be 41 to get Test passed. Ofcourse after adding 20.50 and 20.50 we will get 41. So We have written wrong expected value. Change it to 41 instead of 21.

In Test_MultiplyMethod Assert.AreEqual is supposed to give 20 but we are expecting 100. It must be 20 to get test passed. But Logically after multiplying 10 and 10 we should get 100 then why its actual value is returning 20. Check code of Multiply Method in BasicMaths class.

As we can see that we are using +(Plus) operator between two operand num1 and num2 which should be *(Multiply) operator. Now given code is logically correct one.

Here come my one more windows phone application in the windows phone store. This application is free for all windows phone users. With the help of this application, someone can easily find the exact time of any places and moreover they can compare time between different places. Its works simply as World Time Converter.

About App –
A simple yet elegant World Time application with almost all countries and their capital to add. Compare World Time app help you to view times of different places around the globe.It provides a list of predefined zones from which you can select and you can also add custom defined zones.
Features –
* One screen application. Add and delete from the same screen.
* Search for a city or country
* Long Press on a row to Delete

If you are a Windows Phone developer and have upgraded your system from windows 8 to windows 8.1 then you might have faced “Not enough memory” error problem. If you are facing same problem then stop worrying, Microsoft exposed the symptom, reasons and solution of “Not enough memory” error message and Windows Phone 8 Emulator does not start in Windows 8.1
Here is the link – http://support.microsoft.com/kb/2911380

Reason –

If you are a windows 8.1 user and your system having less than 8 GB ram and moreover you are simultaneously running many programs with developing apps for windows phone, then it is quite obvious that Windows Phone 8 emulator won’t start and will throw a message as given below :

The Windows Phone Emulator wasn’t able to ensure the virtual machine was running: Something happened while starting a virtual machine: ‘Emulator Name’ could not initialize. (Virtual machine ID GUID) Not enough memory in the system to start the virtual machine Emulator Name with ram size 1024 megabytes. (Virtual machine ID GUID)”

Ok fine, but a question can stuck in your mind that,How same program used to run in windows 8 platform but it fails on windows 8.1 ?
Microsoft stated that this problem occurs in Windows 8.1 because the operating system is more conservative than the Windows 8 version about how it allocates memory to maintain consistently high performance. In Windows 8.1, Hyper-V memory management accounts for the memory that is consumed by programs before it starts any emulator instances. Hyper-V did not make this consideration in Windows 8.

Solution –

If the emulator still does not start, you can disable the Hyper-V runtime memory monitoring functionality by adding a MemoryReserve registry.

Sometimes you may want to develop a windows phone app which containing many images to view like WallPaper app for Windows Phone LockScreen, Celebrity album, etc . It is quite easy to display images by using Image Control and passing source path to respective Image Control, but is it enough to just give functionality to see images only ? User always like to keep good images in their phone. so, In that condition user should have an app that can provide facility of save images also. This blog simply shows how you can write code that would allow user to save Image locally in their Save Image Photo album.

Implementation –

Here, you can see some piece of code which containing a function SaveImageToPhotoHub with few statements and a parameter type WriteableBitmap. This SaveImageToPhotoHub function returns either true or false output. To work with this function you just need to pass needed Image as parameter in SaveImageToPhotoHub function.

Note :- To run this code properly your app should have capabilities to access Windows Phone windows phone media library hub. You can simply do this by checking ID_CAP_MEDIALIB_PHOTO from capabilities tab of WMAppManifest.xml

Isn’t it so easy to learn how to save image locally on Windows Phone device. I hope you liked this article and this will help you while writing code for your app.

If you are facing issues while connecting Internet with Windows Phone 8 emulator during deployment process and getting error message like “Windows Phone emulator was not able to connect to Windows Phone operating system. Phone didn’t respond to connect request” or on opening IE(Internet Explorer) of Windows Phone emulator, getting message “We can’t connect to search right now. Make sure airplane mode is turned off, or check your cellular data or Wi-Fi connection” even you system is connected with Internet connection. However when you deploy same Windows Phone application of Windows Phone device(developer unlocked), it works fine without any issues. I can understand this one is weird to consider that same application is behaving differently with same wi-fi connection. I experienced same feeling after upgrading from Visual Studio 2012 to Visual Studio 2013 IDE with Windows 8 OS to Windows 8.1 OS though it was working fine on Windows 8 With Visual Studio 2012. I have tried many tips & tricks available on many websites, blogs and even on MSDN website-[Troubleshooting the Windows Phone 8 Emulator] but I was unable to solve the issues. Finally after using some more steps I am able to connect Internet with Windows phone 8 emulator using WI-FI.

Step 1- Move to “Control Panel\All Control Panel Items\Administrative Tools”, Here remove each and every Virtual Machines listen under.Step 2 – Remove Hyper-V and then Restart the System.Step 3 – After restarting, Install Hyper-V once again.Step 4 – Open Visual Studio and Run any Windows Phone 8 app to start the emulator.Step 5 – It will create again all needed Virtual Machines( you can notice from Hyper-V Manager tools)Step 6 – While loading emulator, it will prompt for letting the emulator access the internet. say yes.Step 7 – Let the emulator and your project fully loadStep 8 – Now you need to shutdown the emulator( by closing directly or use Shift + F5) and close the Visual Studio.Step 9 – Now Open Network and Sharing CentreStep 10 – Click change Adapter Settings (Listed on the left hand side)Step 11 – Now you will see there – “Control Panel\Network and Internet\Network” Connections. some new adapter created by HyperV, they should be called “vEthernet(…)”Step 12 – Here, You need to focus on the vEthernet( Virtual Switch) and vEthernet (Internal Ethernet Port Windows Phone Emulator Internal Switch)Step 13 – Now right click on vEthernet( Virtual Switch) and click on the properties and navigate to the sharing tab.Step 14 – Here, Choose Allow other Network users to connect and choose the vEthernet (Internal Ethernet Port Windows Phone Emulator Internal Switch) as the adapter and then save the changes and close Windows.Step 15- Now open the properties on vEthernet (Internal Ethernet Port Windows Phone Emulator Internal Switch)Step 16 – Here, You need to disable Internet Protocol Version 6 and double click on Internet Protocol Version 4Step 17 – Now, Use the following IP address: 169.254.169.177 Subnet mask:255.255.0.0Step 18 – After entering IP address and Subnet mask. You need to click on advanced button, under the IP settings tab, and then assign an interface metric: 1Step 19 – Now Open your Visual Studio and run the Windows Phone 8 project.Step 20 – Open Internet by using Search button or Internet Explorer of emulator and check Internet access.(Make sure your Wi-fi is working properly)

In my case, It works fine and I’ve shared this tips among some guys and they all solved the issues of Internet with Windows Phone 8 emulator. Hope this might help you also.